﻿using System;
using System.IO;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Globalization;

using CE.Mail;
using CE.User;
using CE.Global;
using CE.Security;
using CE.InputOut;
using CE.Database;
using CE.CarInsurance;
using CXDecryption;

public partial class carinsurance_old_quotes : System.Web.UI.Page
{
    CarUserAccount _account = null;
    CarUserAccountDB _accountdb = null;
    CarUserProfile _profile = null;
    CarUserProfileDB _profiledb = null;
    CarUserContact _contact = null;
    CarUserContactDB _contactdb = null;
    int _currentRow = 0;
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (!IsPostBack)
        {
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "100" && Session[General.UserId].ToString() != "41369")
            {
                btnSubmit.Visible = false;
                hplSearch.Visible = false;
                hplNew.Visible = false;
                hplUploadDocument.Visible = false;

                ddlInsuranceType.Enabled = false;
                ddlGarageType.Enabled = false;

                txtGrossPremium.Enabled = false;
                ddlAnyClaim.Enabled = false;

                ddlVehicleBodyType.Enabled = false;
                txtCTPL.Enabled = false;
                chkCompanyStaff.Enabled = false;
                chkChangePremium.Enabled = false;

                ddlNamedDriver.Enabled = false;

                lblSummaryMessage.Text = Resources.CarInsurance.YourAreNotAuthorizedToViewPage;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.CarInsurance.YourAreNotAuthorizedToViewPage + "');", true);
            }
            else
            {
                ResetAll();
                LoadInsuranceType();
                LoadGarageType();
                LoadCarYear();
               
                LoadOccupation();
                LoadDOB();

                LoadCurrentInsurer();
                ddlInsuranceType.Text = "10";
                ddlInsuranceType_SelectedIndexChanged(null, null);
                LoadBrokerProvider();
                LoadBrokerCoverType();

                int _cryr = dateTimeNow.Year;
                int _styr = 2012;
                ddlTransYear.Items.Clear();

                for (int _year = _cryr; _year >= _styr; _year--)
                {
                    ddlTransYear.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
                }

                if (Request.QueryString["custid"] != null && Request.QueryString["carid"] != null)
                {
                    txtCarId.Text = Request.QueryString["carid"].ToString();

                    DataSet _dsCar = new DataSet();
                    _dsCar = GetCarDetails(Convert.ToInt64(txtCarId.Text));
                    if (_dsCar != null && _dsCar.Tables.Count > 0 && _dsCar.Tables[0].Rows.Count > 0)
                    {
                        txtCustomerId.Text = _dsCar.Tables[0].Rows[0]["RefCEUserId"].ToString();
                        txtCECarPolicyId.Text = _dsCar.Tables[0].Rows[0]["CECarPolicyID"].ToString();
                        if (txtCarId.Text != string.Empty && Convert.ToInt64(txtCarId.Text) > 0
                            && txtCustomerId.Text != string.Empty && Convert.ToInt64(txtCustomerId.Text) > 0
                            && txtCECarPolicyId.Text != string.Empty && Convert.ToInt64(txtCECarPolicyId.Text) > 0)
                        {
                            ShowCarAndPolicyDetail(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCECarPolicyId.Text), Convert.ToInt64(txtCustomerId.Text), 0);
                            LoadPremium();
                            LoadApplicationDetails();
                            LoadPolicyIssued();
                        }
                    }

                }
                else if (Request.QueryString["custid"] != null)
                {
                    Int64 _userID = 0;

                    if (Int64.TryParse(Request.QueryString["custid"].ToString(), out _userID))
                    {
                        txtCustomerId.Text = _userID.ToString();
                        _account = new CarUserAccount();
                        _accountdb = new CarUserAccountDB();

                        _account = _accountdb.GetAccount(_userID);

                        if (_account != null)
                        {
                            ShowCustomerDetail(_account);
                        }
                    }
                }
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("nongg");
        if (Page.IsValid)
        {
            Int64 _userId = 0;

            if (!Int64.TryParse(txtCustomerId.Text, out _userId))
            {
                _userId = 0;
            }

            if (_userId == 0)
            {
                CarUserAccount _userAccount = GetCustomerAccount();

                if (_userAccount != null && _userAccount.CEID > 0)
                {
                    txtCustomerId.Text = _userAccount.CEID.ToString();
                    _userId = _userAccount.CEID;
                }
            }

            _userId = UpdateProfile(_userId);

            if (_userId > 0)
            {
                //txtEmailAddress.ReadOnly = true;

                if (Save(_userId))
                {
                    lblQRefNo.Text = CE.Global.General.GetReferenceNumber(txtCarId.Text.Trim(), ddlBrokerProvider.Text.Trim());
                    SavePremium();
                    SaveAppDetail();
                   
                    if (SavePolicyIssued() > 0)
                    {
                        UpdateAppComplete();
                        Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQRefNo.Text);
                    }
                }
                else
                {
                    lblMessage.Text = "Saving did NOT succeed!";
                }
            }
            else
            {
                lblMessage.Text = "Please fill all require fields completly and correctly.";
            }
        }
    }

    private void LoadPolicyIssued()
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "[sprocCXCRMNonGGTransactionSelectItemByQuoteRefNo]";
        SortedList _sPara = new SortedList();

        _sPara.Add("@QuoteRefNo", lblQRefNo.Text);
        _sPara.Add("@TransactionTypeId", "300");

        DataTable _dtTrans = _db.GetDataTableBySP(_spName, _sPara);
        if (_dtTrans != null && _dtTrans.Rows.Count > 0)
        {
            lblTransID.Text = _dtTrans.Rows[0]["TransactionID"].ToString();
            txtPolicyNo.Text = _dtTrans.Rows[0]["Remarks"].ToString();
            DateTime _dtTransDate = dateTimeNow;
            if (DateTime.TryParse(_dtTrans.Rows[0]["Info1"].ToString(), out _dtTransDate))
            {
                ddlTransDay.Text = _dtTransDate.ToString("dd");
                ddlTransMonth.Text = _dtTransDate.Month.ToString("00");
                ddlTransYear.Text = _dtTransDate.ToString("yyyy");
            }

            float _grossPremium = 0.0f;
            if (float.TryParse(_dtTrans.Rows[0]["FInfo1"].ToString(), out _grossPremium))
            {
                txtPolicyGrossPremium.Text = _grossPremium.ToString("#.00");
            }
        }

        lblMessage.Text = string.Empty;
        lblMessage.ForeColor = System.Drawing.Color.Red;
    }

    private Int64 SavePolicyIssued()
    {
        float _grossPremium;
        if (!float.TryParse(txtPolicyGrossPremium.Text, out _grossPremium))
        {
            lblSummaryMessage.Text = "Gross premium amount is Invalid.";
            return -1;
        }

        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "[sprocCXCRMNonGGTransactionInsertUpdateSingleItem]";
        SortedList _sPara = new SortedList();

        _sPara.Add("@TransactionID", lblTransID.Text);
        if (Session[General.UserRole].ToString() == "100")
        {
            _sPara.Add("@AgentID", Session[General.UserId].ToString());
            _sPara.Add("@AdminID", 0);
        }
        else
        {
            _sPara.Add("@AdminID", Session[General.UserId].ToString());
            _sPara.Add("@AgentID", 0);
        }
        _sPara.Add("@CECarID", txtCarId.Text);
        _sPara.Add("@RefCEUserID", txtCustomerId.Text);
        _sPara.Add("@ProviderCompanyID", ddlBrokerProvider.Text);
        _sPara.Add("@QuoteRefNo", lblQRefNo.Text);
        _sPara.Add("@TransactionTypeId", "300");
        _sPara.Add("@Remarks", txtPolicyNo.Text);

        DateTime _dtTransDate = dateTimeNow;
        

        _dtTransDate = new DateTime(Convert.ToInt32(ddlTransYear.Text), Convert.ToInt32(ddlTransMonth.Text), Convert.ToInt32(ddlTransDay.Text));

        _sPara.Add("@Info1", _dtTransDate.ToString("dd/MMM/yyyy"));
        _sPara.Add("@FInfo1", _grossPremium);
        _sPara.Add("@Status", true);
        Int64 _transID = Convert.ToInt64(_db.ExecuteNonSqlSP(_spName, _sPara));

        LoadPolicyIssued();

        return _transID;

    }

    private int UpdateAppComplete()
    {
        //tblNonGGCarMoreDetails
        MyDatabase _db = new MyDatabase();
        DateTime dtCreated = new DateTime(Convert.ToInt32(ddlApplicationYear.Text), Convert.ToInt32(ddlApplicationMonth.Text), Convert.ToInt32(ddlApplicationDay.Text), dateTimeNow.Hour, dateTimeNow.Minute, dateTimeNow.Second);
        string _strUpdate = "Update tblNonGGCarMoreDetails " +
                            "SET CreatedDate = '" + dtCreated.ToString() + "', " +
                                "ModifiedDate = '" + dtCreated.ToString() + "', " +
                                "SendToProvider = 1, " +
                                "PolicyIssue = 1, " +
                                "Mailing = 1, " +
                                "PaymentStatus = 1, " +
                                "Completed = 1, " +
                                "Info5 = 'OLDQUOTE ' + Cast(dbo.fn_getUTCDateTime() as varchar) " +
                                "WHERE CECarID = " + txtCarId.Text + " AND RefCEUserID = " + txtCustomerId.Text;

        return _db.ExecuteNonSqlStatement(_strUpdate);

    }

    protected void ddlInsuranceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            LoadCarYear();
            if (ddlInsuranceType.Text == "10")
            {
                

                ddlGarageType.Enabled = true;
                rowGarageType.Visible = true;
                ddlCTPL.Enabled = false;
               
                ddlDeduct.Enabled = true;
                ddlProvinceRegistration.Enabled = true;
                ddlAnyClaim.Enabled = true;
                ddlNCB.Enabled = true;
                ddlNamedDriver.Enabled = true;
                ddlDriver1DOBDay.Enabled = false;
                ddlDriver1DOBMonth.Enabled = false;
                ddlDriver1DOBYear.Enabled = false;
                ddlDriver2DOBDay.Enabled = false;
                ddlDriver2DOBMonth.Enabled = false;
                ddlDriver2DOBYear.Enabled = false;

                ddlGarageType.SelectedIndex = 0;
                ddlCarYear.SelectedIndex = 0;
                ddlCarYear_SelectedIndexChanged(null, null);
                ddlCTPL.SelectedIndex = 0;
               
                ddlDeduct.SelectedIndex = 0;
                ddlProvinceRegistration.SelectedIndex = 0;
                ddlAnyClaim.SelectedIndex = 0;
                ddlNCB.SelectedIndex = 0;

                ddlNamedDriver.SelectedIndex = 0;
                ddlNamedDriver_SelectedIndexChanged(null, null);

                ddlDriver1DOBDay.SelectedIndex = 0;
                ddlDriver1DOBMonth.SelectedIndex = 0;
                ddlDriver1DOBYear.SelectedIndex = 0;
                ddlDriver2DOBDay.SelectedIndex = 0;
                ddlDriver2DOBMonth.SelectedIndex = 0;
                ddlDriver2DOBYear.SelectedIndex = 0;
            }
            else if (ddlInsuranceType.Text == "11")
            {
                

                ddlGarageType.Enabled = true;
                rowGarageType.Visible = true;
                ddlCTPL.Enabled = false;
             
                ddlDeduct.Enabled = false;
                ddlProvinceRegistration.Enabled = false;
                ddlAnyClaim.Enabled = false;
                ddlNCB.Enabled = false;
                ddlNamedDriver.Enabled = false;
                ddlDriver1DOBDay.Enabled = false;
                ddlDriver1DOBMonth.Enabled = false;
                ddlDriver1DOBYear.Enabled = false;
                ddlDriver2DOBDay.Enabled = false;
                ddlDriver2DOBMonth.Enabled = false;
                ddlDriver2DOBYear.Enabled = false;

                ddlGarageType.SelectedIndex = 0;
                ddlCarYear.SelectedIndex = 0;
                ddlCarYear_SelectedIndexChanged(null, null);
                ddlCTPL.SelectedIndex = 0;
              
                ddlDeduct.SelectedIndex = 0;
                ddlProvinceRegistration.SelectedIndex = 0;
                ddlAnyClaim.SelectedIndex = 0;
                ddlNCB.SelectedIndex = 0;
                ddlNamedDriver.SelectedIndex = 0;
                ddlNamedDriver_SelectedIndexChanged(null, null);
                ddlDriver1DOBDay.SelectedIndex = 0;
                ddlDriver1DOBMonth.SelectedIndex = 0;
                ddlDriver1DOBYear.SelectedIndex = 0;
                ddlDriver2DOBDay.SelectedIndex = 0;
                ddlDriver2DOBMonth.SelectedIndex = 0;
                ddlDriver2DOBYear.SelectedIndex = 0;
            }
            else if (ddlInsuranceType.Text == "21")
            {
               

                ddlGarageType.Enabled = true;
                rowGarageType.Visible = true;
                ddlCTPL.Enabled = false;
              
                ddlDeduct.Enabled = true;
                ddlProvinceRegistration.Enabled = false;
                ddlAnyClaim.Enabled = false;
                ddlNCB.Enabled = false;
                ddlNamedDriver.Enabled = false;
                ddlDriver1DOBDay.Enabled = false;
                ddlDriver1DOBMonth.Enabled = false;
                ddlDriver1DOBYear.Enabled = false;
                ddlDriver2DOBDay.Enabled = false;
                ddlDriver2DOBMonth.Enabled = false;
                ddlDriver2DOBYear.Enabled = false;

                ddlGarageType.SelectedIndex = 0;
                ddlCarYear.SelectedIndex = 0;
                ddlCarYear_SelectedIndexChanged(null, null);
                ddlCTPL.SelectedIndex = 0;
               
                ddlDeduct.SelectedIndex = 0;
                ddlProvinceRegistration.SelectedIndex = 0;
                ddlAnyClaim.SelectedIndex = 0;
                ddlNCB.SelectedIndex = 0;
                ddlNamedDriver.SelectedIndex = 0;
                ddlNamedDriver_SelectedIndexChanged(null, null);
                ddlDriver1DOBDay.SelectedIndex = 0;
                ddlDriver1DOBMonth.SelectedIndex = 0;
                ddlDriver1DOBYear.SelectedIndex = 0;
                ddlDriver2DOBDay.SelectedIndex = 0;
                ddlDriver2DOBMonth.SelectedIndex = 0;
                ddlDriver2DOBYear.SelectedIndex = 0;
            }
            else if (ddlInsuranceType.Text == "31")
            {
               

                ddlGarageType.Enabled = true;
                rowGarageType.Visible = true;
                ddlCTPL.Enabled = false;
               
                ddlDeduct.Enabled = true;
                ddlProvinceRegistration.Enabled = false;
                ddlAnyClaim.Enabled = false;
                ddlNCB.Enabled = false;
                ddlNamedDriver.Enabled = false;
                ddlDriver1DOBDay.Enabled = false;
                ddlDriver1DOBMonth.Enabled = false;
                ddlDriver1DOBYear.Enabled = false;
                ddlDriver2DOBDay.Enabled = false;
                ddlDriver2DOBMonth.Enabled = false;
                ddlDriver2DOBYear.Enabled = false;

                ddlGarageType.SelectedIndex = 0;
                ddlCarYear.SelectedIndex = 0;
                ddlCarYear_SelectedIndexChanged(null, null);
                ddlCTPL.SelectedIndex = 0;
               
                ddlDeduct.SelectedIndex = 0;
                ddlProvinceRegistration.SelectedIndex = 0;
                ddlAnyClaim.SelectedIndex = 0;
                ddlNCB.SelectedIndex = 0;
                ddlNamedDriver.SelectedIndex = 0;
                ddlNamedDriver_SelectedIndexChanged(null, null);
                ddlDriver1DOBDay.SelectedIndex = 0;
                ddlDriver1DOBMonth.SelectedIndex = 0;
                ddlDriver1DOBYear.SelectedIndex = 0;
                ddlDriver2DOBDay.SelectedIndex = 0;
                ddlDriver2DOBMonth.SelectedIndex = 0;
                ddlDriver2DOBYear.SelectedIndex = 0;
            }
            else if (ddlInsuranceType.Text == "30")
            {
                

                ddlGarageType.Enabled = false;
                rowGarageType.Visible = false;
                ddlCTPL.Enabled = true;
              
                ddlDeduct.Enabled = true;
                ddlProvinceRegistration.Enabled = false;
                ddlAnyClaim.Enabled = false;
                ddlNCB.Enabled = false;
                ddlNamedDriver.Enabled = false;
                ddlDriver1DOBDay.Enabled = false;
                ddlDriver1DOBMonth.Enabled = false;
                ddlDriver1DOBYear.Enabled = false;
                ddlDriver2DOBDay.Enabled = false;
                ddlDriver2DOBMonth.Enabled = false;
                ddlDriver2DOBYear.Enabled = false;

                ddlGarageType.SelectedIndex = 0;
                ddlCarYear.SelectedIndex = 0;
                ddlCarYear_SelectedIndexChanged(null, null);
                ddlCTPL.SelectedIndex = 0;
             
                ddlDeduct.SelectedIndex = 0;
                ddlProvinceRegistration.SelectedIndex = 0;
                ddlAnyClaim.SelectedIndex = 0;
                ddlNCB.SelectedIndex = 0;
                ddlNamedDriver.SelectedIndex = 0;
                ddlNamedDriver_SelectedIndexChanged(null, null);
                ddlDriver1DOBDay.SelectedIndex = 0;
                ddlDriver1DOBMonth.SelectedIndex = 0;
                ddlDriver1DOBYear.SelectedIndex = 0;
                ddlDriver2DOBDay.SelectedIndex = 0;
                ddlDriver2DOBMonth.SelectedIndex = 0;
                ddlDriver2DOBYear.SelectedIndex = 0;
            }
            
            ValidateControlEnable();
            setControlVisible();
            ddlBrokerProvider.SelectedIndex = 0;
            ddlBrokerProvider_SelectedIndexChanged(sender, e);
        }
        catch
        {

        }
    }

    protected void ddlGarageType_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlBrokerProvider.SelectedIndex = 0;
        ddlBrokerProvider_SelectedIndexChanged(sender, e);
    }

   

    protected void ddlBrokerGarageType_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadBrokerDefault();
    }

    protected void ddlCarYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarYear.Text == "-1")
        {
            ClearAllList();
        }
        else
        {
            GetCarMakeList(ddlCarYear.Text, ddlCarMake);
            if (ddlCarMake.Items.Count > 0)
            {
                ddlCarMake.SelectedIndex = 0;
                ddlCarMake_SelectedIndexChanged(sender, e);
            }
        }
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlCarYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlCarYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
        }
    }

    

    protected void ddlAnyClaim_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlAnyClaim.Text == "1")
        {
            ddlNCB.Items.Clear();
            ddlNCB.Items.Add(new ListItem("No NCD", "0"));
        }
        else
        {
            ddlNCB.Items.Clear();
            ddlNCB.Items.Add(new ListItem(Resources.General.Select, "-1"));
            ddlNCB.Items.Add(new ListItem("0 %", "0"));
            ddlNCB.Items.Add(new ListItem("20 %", "20"));
            ddlNCB.Items.Add(new ListItem("30 %", "30"));
            ddlNCB.Items.Add(new ListItem("40 %", "40"));
            ddlNCB.Items.Add(new ListItem("50 %", "50"));
        }
    }

    protected void ResetAll()
    {
        //txtCustomerID CAN NOT CLEAR
        txtCarId.Text = "0";
        txtCECarPolicyId.Text = "0";
        txtCustomerId.Text = "0";
       
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        txtSumInsured.Text = "0";
        lblSumInsured.Text = "0";
        txtGroupNo.Text = "-1";
    }

    public void ValidateControlEnable()
    {
        if (ddlInsuranceType.Text == "10")
        {
            rfvGarageType.Enabled = true;
            rfvCarYear.Enabled = true;
            rfvCarMake.Enabled = true;
            rfvModelBodyCCDoor.Enabled = true;
            rfvCTPL.Enabled = false;
         
            rfvProvinceRegistration.Enabled = true;
            rfvAnyClaim.Enabled = true;
            rfvNCB.Enabled = true;


            
            rfvCurrentInsurer.Enabled = true;
          
            rfvEmailAddress.Enabled = true;
            revEmailAddress.Enabled = true;
            rfvGender.Enabled = true;
            rfvDOBDay.Enabled = true;
            rfvDOBMonth.Enabled = true;
            rfvDOBYear.Enabled = true;
            rfvOccupation.Enabled = true;
        }
        else if (ddlInsuranceType.Text == "11")
        {
            rfvGarageType.Enabled = true;
            rfvCarYear.Enabled = true;
            rfvCarMake.Enabled = true;
            rfvModelBodyCCDoor.Enabled = true;
            rfvCTPL.Enabled = false;
           
            rfvProvinceRegistration.Enabled = false;
            rfvAnyClaim.Enabled = false;
            rfvNCB.Enabled = false;
            rfvDriver1DOBDay.Enabled = false;
            rfvDriver1DOBMonth.Enabled = false;
            rfvDriver1DOBYear.Enabled = false;
            rfvDriver2DOBDay.Enabled = false;
            rfvDriver2DOBMonth.Enabled = false;
            rfvDriver2DOBYear.Enabled = false;
           
            rfvCurrentInsurer.Enabled = true;
          
            rfvEmailAddress.Enabled = true;
            revEmailAddress.Enabled = true;
            rfvGender.Enabled = true;
            rfvDOBDay.Enabled = true;
            rfvDOBMonth.Enabled = true;
            rfvDOBYear.Enabled = true;
            rfvOccupation.Enabled = true;
        }
        else if (ddlInsuranceType.Text == "21")
        {
            rfvGarageType.Enabled = true;
            rfvCarYear.Enabled = true;
            rfvCarMake.Enabled = true;
            rfvModelBodyCCDoor.Enabled = true;
            rfvCTPL.Enabled = false;
            
            rfvProvinceRegistration.Enabled = false;
            rfvAnyClaim.Enabled = false;
            rfvNCB.Enabled = false;
            rfvDriver1DOBDay.Enabled = false;
            rfvDriver1DOBMonth.Enabled = false;
            rfvDriver1DOBYear.Enabled = false;
            rfvDriver2DOBDay.Enabled = false;
            rfvDriver2DOBMonth.Enabled = false;
            rfvDriver2DOBYear.Enabled = false;
            
            rfvCurrentInsurer.Enabled = true;
           
            rfvEmailAddress.Enabled = true;
            revEmailAddress.Enabled = true;
            rfvGender.Enabled = true;
            rfvDOBDay.Enabled = true;
            rfvDOBMonth.Enabled = true;
            rfvDOBYear.Enabled = true;
            rfvOccupation.Enabled = true;
        }
        else if (ddlInsuranceType.Text == "31")
        {
            rfvGarageType.Enabled = true;
            rfvCarYear.Enabled = true;
            rfvCarMake.Enabled = true;
            rfvModelBodyCCDoor.Enabled = true;
            rfvCTPL.Enabled = false;
            
            rfvProvinceRegistration.Enabled = false;
            rfvAnyClaim.Enabled = false;
            rfvNCB.Enabled = false;
            rfvDriver1DOBDay.Enabled = false;
            rfvDriver1DOBMonth.Enabled = false;
            rfvDriver1DOBYear.Enabled = false;
            rfvDriver2DOBDay.Enabled = false;
            rfvDriver2DOBMonth.Enabled = false;
            rfvDriver2DOBYear.Enabled = false;
            
            rfvCurrentInsurer.Enabled = true;
           
            rfvEmailAddress.Enabled = true;
            revEmailAddress.Enabled = true;
            rfvGender.Enabled = true;
            rfvDOBDay.Enabled = true;
            rfvDOBMonth.Enabled = true;
            rfvDOBYear.Enabled = true;
            rfvOccupation.Enabled = true;
        }
        else if (ddlInsuranceType.Text == "30")
        {
            rfvGarageType.Enabled = false;
            rfvCarYear.Enabled = true;
            rfvCarMake.Enabled = true;
            rfvModelBodyCCDoor.Enabled = true;
            rfvCTPL.Enabled = true;
            
            rfvProvinceRegistration.Enabled = false;
            rfvAnyClaim.Enabled = false;
            rfvNCB.Enabled = false;
            rfvDriver1DOBDay.Enabled = false;
            rfvDriver1DOBMonth.Enabled = false;
            rfvDriver1DOBYear.Enabled = false;
            rfvDriver2DOBDay.Enabled = false;
            rfvDriver2DOBMonth.Enabled = false;
            rfvDriver2DOBYear.Enabled = false;
            
            rfvCurrentInsurer.Enabled = true;
           
            rfvEmailAddress.Enabled = true;
            revEmailAddress.Enabled = true;
            rfvGender.Enabled = true;
            rfvDOBDay.Enabled = true;
            rfvDOBMonth.Enabled = true;
            rfvDOBYear.Enabled = true;
            rfvOccupation.Enabled = true;
        }
    }

    public void LoadInsuranceType()
    {
        ddlInsuranceType.Items.Clear();
        ddlInsuranceType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOne, "10"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOneLowCost, "11"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassTwoPlus, "21"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThreePlus, "31"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThree, "30"));
    }

    public void LoadGarageType()
    {
        ddlGarageType.Items.Clear();
        ddlGarageType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlGarageType.Items.Add(new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
        ddlGarageType.Items.Add(new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
    }



    public void LoadDate(DropDownList ddl)
    {
        string val = "";
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem(Resources.CarInsurance.Day, "-1"));
        for (int _date = 1; _date <= 31; _date++)
        {
            val = _date.ToString();
            if (_date < 10)
            {
                val = "0" + _date.ToString();
            }
            ddl.Items.Add(new ListItem(val, val));
        }
    }

    public void LoadMonth(DropDownList ddl)
    {
        string val = "";
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem(Resources.CarInsurance.Month, "-1"));
        string monthname = Resources.General.Select;
        for (int _month = 1; _month <= 12; _month++)
        {
            val = _month.ToString();
            if (_month < 10)
            {
                val = "0" + _month.ToString();
            }
            else
            {
                val = _month.ToString();
            }
            if (_month == 1)
            {
                monthname = Resources.MonthResource.January;
            }
            else if (_month == 2)
            {
                monthname = Resources.MonthResource.February;
            }
            else if (_month == 3)
            {
                monthname = Resources.MonthResource.March;
            }
            else if (_month == 4)
            {
                monthname = Resources.MonthResource.April;
            }
            else if (_month == 5)
            {
                monthname = Resources.MonthResource.May;
            }
            else if (_month == 6)
            {
                monthname = Resources.MonthResource.June;
            }
            else if (_month == 7)
            {
                monthname = Resources.MonthResource.July;
            }
            else if (_month == 8)
            {
                monthname = Resources.MonthResource.August;
            }
            else if (_month == 9)
            {
                monthname = Resources.MonthResource.September;
            }
            else if (_month == 10)
            {
                monthname = Resources.MonthResource.October;
            }
            else if (_month == 11)
            {
                monthname = Resources.MonthResource.November;
            }
            else if (_month == 12)
            {
                monthname = Resources.MonthResource.December;
            }
            //ddl.Items.Clear();
            ddl.Items.Add(new ListItem(monthname, val));
        }
    }

    public void LoadYear(DropDownList ddl, int start, int end)
    {
        string ddlval = "";
        string ddltxt = "";
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem(Resources.CarInsurance.Year, "-1"));
        for (int _year = start; _year >= end; _year--)
        {
            ddlval = _year.ToString();
            ddltxt = _year.ToString();
            if (lblLangOption.Text == "1")
            {
                ddltxt = (_year + 543).ToString();
            }
            ddl.Items.Add(new ListItem(ddltxt, ddlval));
        }
    }

    public void LoadOccupation()
    {
        DataTable dtOccupation = General.GetComboItem(Resources.CarInsurance.OccupationList, Resources.CarInsurance.OccupationSortBy, true);
        ddlOccupation.DataSource = dtOccupation;
        ddlOccupation.DataTextField = dtOccupation.Columns[0].ColumnName.ToString();
        ddlOccupation.DataValueField = dtOccupation.Columns[1].ColumnName.ToString();
        ddlOccupation.DataBind();
        ddlOccupation.Items.Insert(0, new ListItem(Resources.General.Select, "-1"));
    }

    public void LoadDOB()
    {
        int intStartYear = dateTimeNow.Year - 18;
        int intEndYear = dateTimeNow.Year - 90;

        LoadDate(ddlDOBDay);
        LoadMonth(ddlDOBMonth);
        LoadYear(ddlDOBYear, intStartYear, intEndYear);

        LoadDate(ddlDriver1DOBDay);
        LoadMonth(ddlDriver1DOBMonth);
        LoadYear(ddlDriver1DOBYear, intStartYear, intEndYear);

        LoadDate(ddlDriver2DOBDay);
        LoadMonth(ddlDriver2DOBMonth);
        LoadYear(ddlDriver2DOBYear, intStartYear, intEndYear);
    }

    private void LoadCarYear()
    {
        int _yearCount = 10;
        ddlCarYear.Items.Clear();

        if (ddlInsuranceType.Text != "-1")
        {
            if (Convert.ToInt32(ddlInsuranceType.Text) >= 20)
            {
                _yearCount = 20;
            }
            int _startYear = dateTimeNow.Year - _yearCount;
            int _endYear = dateTimeNow.Year;
            for (int i = _endYear; i >= _startYear; i--)
            {
                if (lblLangOption.Text.Trim() != "1")
                {
                    ddlCarYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                else
                {
                    ddlCarYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
                }
            }
        }
        ddlCarYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    public void LoadCurrentInsurer()
    {
        DataTable dtPreInsurerComp = General.GetComboItem(Resources.DBTable.PreInsurer, Resources.DBTable.OrderByField, true);
        ddlCurrentInsurer.DataSource = dtPreInsurerComp;
        ddlCurrentInsurer.DataTextField = dtPreInsurerComp.Columns[0].ColumnName.ToString();
        ddlCurrentInsurer.DataValueField = dtPreInsurerComp.Columns[1].ColumnName.ToString();
        ddlCurrentInsurer.DataBind();
        ddlCurrentInsurer.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    private CarUserAccount GetCustomerAccount()
    {
        CarUserAccount _caruseraccount = new CarUserAccount();
        CarUserAccountDB _caruseraccountdb = new CarUserAccountDB();
        _caruseraccount = _caruseraccountdb.GetUserAccount(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));

       

        return _caruseraccount;

    }

    public DataSet GetCarDetails(Int64 CarId)
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "sprocCXCRMCarDetailsSingleItemByCarId";

        SortedList _spara = new SortedList();
        _spara.Add("@CarId", CarId);

        DataSet _ds = _db.GetDataSet(_spName, _spara);

        return _ds;
    }

    private void ShowCarAndPolicyDetail(Int64 CarId, Int64 PolicyId, Int64 UserId, Int16 QuoteRenewStatus)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        _cardetail = _cardetaildb.GetCar(CarId, UserId);

        CarPolicy _carpolicy = new CarPolicy();
        CarPolicyDB _carpolicydb = new CarPolicyDB();
        _carpolicy = _carpolicydb.GetCarPolicy(CarId, PolicyId, UserId);

        if (_carpolicy != null && _cardetail != null)
        {
            SetProperty(_carpolicy, _cardetail, QuoteRenewStatus);
        }

        _cardetail = null;
        _cardetaildb = null;

        _carpolicy = null;
        _carpolicydb = null;
    }

    private void SetProperty(CarPolicy _CarPolicy, CarDetailTH _CarDetail, Int16 QuoteRenewStatus)
    {
        CultureInfo ci = new CultureInfo("th-TH");
        if (lblLangOption.Text == "2")
        {
            ci = new CultureInfo("en-US");
        }

        _account = new CarUserAccount();
        _accountdb = new CarUserAccountDB();

        _account = _accountdb.GetAccount(_CarDetail.RefCEUserId);

        if (_account != null)
        {
            ShowCustomerDetail(_account);
        }
        else
        {
            lblMessage.Text = "[ERROR] Customer detail was not found!<br/><br/>Location:SetProperty(CarPolicy _CarPolicy, CarDetailTH _CarDetail, Int16 QuoteRenewStatus)";
        }

        if (_account != null)
        {
            ddlInsuranceType.Text = _CarPolicy.InsuranceType.ToString();
            ddlInsuranceType_SelectedIndexChanged(null, null);
            ddlGarageType.Text = _CarPolicy.GarageType.ToString();
            ddlGarageType_SelectedIndexChanged(null, null);
            LoadCarYear();
            ddlCarYear.Text = _CarDetail.ManufactYear.ToString();
            ddlCarYear_SelectedIndexChanged(null, null);
            ddlCarMake.Text = _CarDetail.CarMakeName;
            ddlCarMake_SelectedIndexChanged(null, null);
            string _tempDesc = _CarDetail.CarModelName + " " + _CarDetail.Body + " " + _CarDetail.CC + "cc " + _CarDetail.Door.ToString() + " doors";

            ddlModelBodyCCDoor.Text = _tempDesc;
            ddlModelBodyCCDoor_SelectedIndexChanged(null, null);
            ddlCurrentInsurer.Text = _CarDetail.Info1;
            txtGroupNo.Text = _CarDetail.GroupNo.ToString();
            lblCarVehicleType.Text = _CarDetail.Info2;
            if (_CarDetail.Info3 == "110" || _CarDetail.Info3 == "210" || _CarDetail.Info3 == "320")
            {
                ddlVehicleType.Text = "110";
            }
            else
            {
                ddlVehicleType.Text = "120";
            }
           
          
            lblSumInsured.Text = Convert.ToInt32(txtSumInsured.Text).ToString("#,000");
          
            ddlDeduct.SelectedValue = Convert.ToInt32(_CarPolicy.Deductible) == 0 ? "0" : "-1";
            ddlProvinceRegistration.Text = _CarPolicy.ProvinceRegistration;

            ddlCommenceDay.Text = _CarPolicy.CoverageCommenceDate.Day.ToString("00");
            ddlCommenceMonth.Text = _CarPolicy.CoverageCommenceDate.Month.ToString("00");
            ddlCommenceYear.Text = _CarPolicy.CoverageCommenceDate.Year.ToString("0000");

            ddlAnyClaim.Text = Convert.ToInt16(_CarPolicy.IsClaimLastYear).ToString();
            ddlNamedDriver.Text = _CarPolicy.NoOfDriver.ToString();
            ddlNamedDriver_SelectedIndexChanged(null, null);
            ddlCTPL.Text = Convert.ToInt16(_CarPolicy.IsCTPL).ToString();
            ddlNCB.Text = _CarPolicy.NCDPercent.ToString();

          

            txtCustomerName.Text = _CarDetail.Info8 + " " + _CarDetail.Info7;
            txtContactNumber.Text = _CarDetail.Info6;
            txtEmailAddress.Text = _CarDetail.Info5;



            if (_CarPolicy.Info6.Length > 0 && _CarPolicy.Info7.Length > 0)
            {
                divLastYearRefNo.Visible = true;
                lblLastYearCarID.Text = _CarPolicy.Info6;
                lblLastYearRefNo.Text = _CarPolicy.Info7;
            }

            if (_CarPolicy.NoOfDriver > 0)
            {
                DataTable _dtDriver = new DataTable();
                CarDriverDB _carDriverdb = new CarDriverDB();
                _dtDriver = _carDriverdb.GetDriverList(_CarDetail.CarId, _CarDetail.RefCEUserId);
                if (_dtDriver != null && _dtDriver.Rows.Count > 0)
                {
                    txtDriverId1.Text = _dtDriver.Rows[0]["CarDriverId"].ToString();
                    DateTime _DriverDOB1 = new DateTime();
                    DateTime.TryParse(_dtDriver.Rows[0]["DOB"].ToString(), out _DriverDOB1);
                    ddlDriver1DOBDay.Text = _DriverDOB1.Day.ToString("00");
                    ddlDriver1DOBMonth.Text = _DriverDOB1.Month.ToString("00");
                    ddlDriver1DOBYear.Text = _DriverDOB1.Year.ToString("0000");
                    if (_dtDriver != null && _dtDriver.Rows.Count > 1)
                    {
                        txtDriverId2.Text = _dtDriver.Rows[1]["CarDriverId"].ToString();
                        DateTime _DriverDOB2 = new DateTime();
                        DateTime.TryParse(_dtDriver.Rows[1]["CarDriverId"].ToString(), out _DriverDOB2);
                        ddlDriver2DOBDay.Text = _DriverDOB2.Day.ToString("00");
                        ddlDriver2DOBMonth.Text = _DriverDOB2.Month.ToString("00");
                        ddlDriver2DOBYear.Text = _DriverDOB2.Year.ToString("0000");
                    }
                }

            }
            ValidateControlEnable();
        }
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocKawnaGetCarModelDescListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][0].ToString()));
            }
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
          
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void setControlVisible()
    {
        if (ddlCTPL.Enabled == false)
        {
            trIsCTPL.Visible = false;
        }
        else
        {
            trIsCTPL.Visible = true;
        }

      

        if (ddlProvinceRegistration.Enabled == false)
        {
            trProvinceRegistration.Visible = false;
        }
        else
        {
            trProvinceRegistration.Visible = true;
        }
        if (ddlAnyClaim.Enabled == false)
        {
            trIsClaim.Visible = false;
        }
        else
        {
            trIsClaim.Visible = true;
        }
        if (ddlNCB.Enabled == false)
        {
            trNCB.Visible = false;
        }
        else
        {
            trNCB.Visible = true;
        }

        if (ddlDeduct.Enabled == false)
        {
            trDEC.Visible = false;
        }
        else
        {
            trDEC.Visible = true;
        }
    }

    #region Save & Update

    private bool Save(Int64 UserID)
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        CarUserProfileDB _profiledb = new CarUserProfileDB();
        CarUserProfile _profile = new CarUserProfile();

        CarUserContact _contact = new CarUserContact();
        CarUserContactDB _contactdb = new CarUserContactDB();

        if (UserID > 0)
        {
            _profile = _profiledb.GetProfile(UserID);
            _contact = _contactdb.GetContact(UserID);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;//txtFirstName.Text.Trim();
                }
                _car.Info9 = _profile.Gender.ToString(); //ddlGender.GetGender();
                _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                _car.Info11 = _profile.Occupation.ToString();// ddlOccupation.GetOccupation();
                _car.Info12 = _profile.JobNature;//ddlJobNature.GetJobNature();
                _car.Info13 = _profile.MaritalStatus.ToString();//ddlMaritalStatus.GetMaritalStatus();
                _car.Info14 = "0"; //ddlYearDriveSg.Text;
                _car.Info15 = _profile.Salutation;//ddlSalutation.GetSalutation();
                _profile = null;
                _contact = null;
            }
        }

        if (txtCarId.Text != string.Empty && txtCarId.Text != "0")
        {
            _car = _cardb.GetCar(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtCustomerId.Text.Trim()));
        }

        if (_car == null)
        {
            _car = new CarDetailTH();
        }

        _car.ManufactYear = Convert.ToInt32(ddlCarYear.Text);

        if (Session[General.UserId] != "0")
        {
            _car.Info2 = Session[General.UserId].ToString();
            _car.Info3 = dateTimeNow.ToString();
        }

        _car.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);

        string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;


        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = ddlVehicleType.Text;
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "210";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "220";
            }
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "320";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "340"; //Disabled, No Packages
            }
        }
     
        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = UserID;
        _car.ViewedDetailId = 0;// Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
        _car.CurrentStep = 1;
        _car.TotalStep = 4;
        _car.Info1 = ddlCurrentInsurer.Text; //Current Insurer ID

        _carresult = _cardb.Insert(_car);

        _car = null;
        _cardb = null;
     

       
        if (_carresult > 0)
        {
            txtCarId.Text = _carresult.ToString();
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = Convert.ToInt64(txtCarId.Text);

            Int64 _carpolicyid = 0;

            if (txtCECarPolicyId.Text != string.Empty && txtCECarPolicyId.Text != "0")
            {
                _carpolicyid = Convert.ToInt64(txtCECarPolicyId.Text);
                _carpolicy.CECarPolicyId = _carpolicyid;
               
                _carpolicy.Info5 = "UPDATE";
               
            }
            else
            {
               
                _carpolicy.Info4 = "NEW";
               
            }

            lblMessage.Text = "";
            if (Session[General.UserId] != null)
            {
                _carpolicy.Info2 = Session[General.UserId].ToString();
                _carpolicy.Info3 = dateTimeNow.ToString();
            }

            _carpolicy.CECarId = _carId;
            _carpolicy.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
            _carpolicy.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _carpolicy.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
            _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text);
            _carpolicy.ProvinceRegistration = ddlProvinceRegistration.Text;
            _carpolicy.UseOfVehicle = "N/A";//ddlUseOfVehicle.Text;
            int _iDay = Convert.ToInt32(ddlCommenceDay.Text);
            int _iMonth = Convert.ToInt32(ddlCommenceMonth.Text);
            int _iYear = Convert.ToInt32(ddlCommenceYear.Text);
            _carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay);
            _carpolicy.IsRedPlate = false; //rdoYesRedPlate.Checked;

            

            _carpolicy.IsAddAccMod = false;
            _carpolicy.AddAccModAmount = 0;

            _carpolicy.NCDPercent = Convert.ToInt32(ddlNCB.Text);
            if (ddlAnyClaim.Text == "1")
            {
                _carpolicy.IsClaimLastYear = true;
            }
            else
            {
                _carpolicy.IsClaimLastYear = false;
            }
            if (ddlCTPL.Text == "1")
            {
                _carpolicy.IsCTPL = true;
            }
            else
            {
                _carpolicy.IsCTPL = false;
            }

            if (ddlNamedDriver.Text != "0")
            {
                _carpolicy.IsAddDriver = true;
                _carpolicy.NoOfDriver = Convert.ToInt16(ddlNamedDriver.Text);
            }
            else
            {
                _carpolicy.IsAddDriver = false;
                _carpolicy.NoOfDriver = 0;
            }
           
            _carpolicy.Deductible = Convert.ToInt16(ddlDeduct.SelectedValue);
            _carpolicy.CurrentInsurer = ddlCurrentInsurer.SelectedItem.Text;
            _carpolicy.RefCEUserId = UserID;
          
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;
            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                txtCECarPolicyId.Text = _policyresult.ToString();

                lblMessage.Text += "<br>Car policy saved successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblMessage.Text = "Car policy did not save successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }

            CarDriver _cardriver = new CarDriver();
            CarDriverDB _cardriverdb = new CarDriverDB();

            if (ddlNamedDriver.Text != "0")
            {
                int _drivercount = Convert.ToInt32(ddlNamedDriver.Text);
                int _insertcount = 0;
                _cardriverdb.UpdateAllStatus(_carId, UserID);

                for (int i = 1; i <= _drivercount; i++)
                {
                    _cardriver.StepId = 1;
                    _cardriver.RerCEUserId = UserID;
                    _cardriver.CECarId = _carId;
                    if (i == 1)
                    {
                        _cardriver.CarDriverId = Convert.ToInt64(txtDriverId1.Text);
                        DateTime _dtDOB1 = new DateTime(Convert.ToInt32(ddlDriver1DOBYear.Text), Convert.ToInt32(ddlDriver1DOBMonth.Text), Convert.ToInt32(ddlDriver1DOBDay.Text));
                        _cardriver.DOB = _dtDOB1;
                        _cardriver.Status = "Active";
                    }
                    else if (i == 2)
                    {
                        _cardriver.CarDriverId = Convert.ToInt64(txtDriverId2.Text);
                        DateTime _dtDOB2 = new DateTime(Convert.ToInt32(ddlDriver2DOBYear.Text), Convert.ToInt32(ddlDriver2DOBMonth.Text), Convert.ToInt32(ddlDriver2DOBDay.Text));
                        _cardriver.DOB = _dtDOB2;
                        _cardriver.Status = "Active";
                    }

                    _cardriver.ViewedDetailId = 0;//Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
                    if (_cardriverdb.Insert(_cardriver) > 0)
                    {
                        _insertcount++;
                    }
                }

                _cardriverdb = null;
                _cardriver = null;

                if (_insertcount == _drivercount)
                {
                    lblMessage.Text += "<br>All drivers are successfully saved!";
                    lblMessage.ForeColor = System.Drawing.Color.Blue;
                }
                else
                {
                    lblMessage.Text += "<br>All drivers are did not saved!";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return false;
                }
            }
            else
            {
                _cardriverdb.UpdateAllStatus(_carId, UserID);
            }

            _carpolicy = null;
            _carpolicydb = null;
        }

        return _policyresult > 0;
    }

    private Int64 UpdateProfile(Int64 UserId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _account = new CarUserAccount();
            _accountdb = new CarUserAccountDB();

            _profile = new CarUserProfile();
            _profiledb = new CarUserProfileDB();

            _contact = new CarUserContact();
            _contactdb = new CarUserContactDB();

            _account = _accountdb.GetAccount(UserId);
            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_account != null)
            {
                if (_account.UserTypeId == 1001)
                {
                    _account.Email = txtEmailAddress.Text;
                    _account.AuthCode = txtContactNumber.Text;
                    _account.RefCEUserID = Convert.ToInt64(Session[General.UserId].ToString());
                    _account.Status = true;
                    _retValue = _accountdb.Insert(_account);


                }
                else
                {
                    _retValue = _account.CEID;
                }
            }

            if (_retValue > 0 && _profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
              
                _profile.SurName = txtCustomerName.Text;
                DateTime _dtDOB = new DateTime(Convert.ToInt32(ddlDOBYear.Text), Convert.ToInt32(ddlDOBMonth.Text), Convert.ToInt32(ddlDOBDay.Text));
                _profile.DOB = _dtDOB;
                _profile.Gender = Convert.ToChar(ddlGender.Text);

                _profile.MaritalStatus = -1;// Convert.ToInt32(ddlMaritalStatus.GetMaritalStatus());
                _profile.JobNature = "";// ddlJobNature.GetJobNature();
                _profile.Occupation = Convert.ToInt32(ddlOccupation.Text);
                _profile.YearDriveSg = 0;//Convert.ToInt16(ddlYearDriveSg.Text);
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    if (_account.UserTypeId == 1001)
                    {
                        _contact.Email = txtEmailAddress.Text;
                    }
                    _contact.Mobile = txtContactNumber.Text;
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                    _retValue = 0;
                }

                if (_retValue > 0)
                {
                    _retValue = UserId;
                }
                else
                {
                    _retValue = 0;
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;


        CarUserAccount _useraccount = new CarUserAccount();
        CarUserAccountDB _useraccountdb = new CarUserAccountDB();

        CarUserProfile _userprofile = new CarUserProfile();
        CarUserProfileDB _userprofiledb = new CarUserProfileDB();
        CarUserContact _contact = new CarUserContact();
        CarUserContactDB _contactdb = new CarUserContactDB();

        long _result = -1;
        _useraccount.Email = txtEmailAddress.Text.ToLower();
        string _authcode = txtContactNumber.Text;

        _useraccount.AuthCode = _authcode;
        _useraccount.UserId = "CEUSERIDBYTEMPADMIN";
        _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
        _useraccount.IsAcceptTC = false;
        _useraccount.Status = true;
        _useraccount.RefCEUserID = Convert.ToInt64(Session[General.UserId].ToString());
        _result = _useraccountdb.Insert(_useraccount);
        _useraccount.CEID = _result;
        _retVal = _useraccount.CEID;

        if (_result > 0)
        {
            txtCustomerId.Text = _result.ToString();
            _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
            _userprofile.FirstName = "";
            _userprofile.SurName = Server.HtmlEncode(txtCustomerName.Text);

            DateTime _dtDOB = new DateTime(1900, 1, 1);
            _dtDOB = new DateTime(Convert.ToInt32(ddlDOBYear.Text), Convert.ToInt32(ddlDOBMonth.Text), Convert.ToInt32(ddlDOBDay.Text));
            _userprofile.DOB = _dtDOB;
            _userprofile.Gender = Convert.ToChar(ddlGender.Text);
            _userprofile.Occupation = Convert.ToInt32(ddlOccupation.Text);
            _userprofile.Status = "Complete";
            _userprofile.RefCEUserId = Convert.ToInt64(txtCustomerId.Text);
            _userprofile.IsAcceptTC = true;
            _result = _userprofiledb.Insert(_userprofile);

            _contact.Email = _useraccount.Email;
            _contact.Mobile = txtContactNumber.Text;
            _contact.Status = true;
            _contact.RefCEUserId = _useraccount.CEID;
            _result = _contactdb.Insert(_contact);
        }

        return _retVal;

        #endregion
    }

    #endregion

    private void ShowCustomerDetail(CarUserAccount UserAccount)
    {
        _profile = new CarUserProfile();
        _profiledb = new CarUserProfileDB();
        _contact = new CarUserContact();
        _contactdb = new CarUserContactDB();

        _profile = _profiledb.GetProfile(UserAccount.CEID);
        _profiledb = null;

        if (_profile != null)
        {
            
            txtCustomerName.Text = _profile.FirstName + " " + _profile.SurName;

            ddlOccupation.Text = _profile.Occupation.ToString();
            ddlGender.Text = _profile.Gender.ToString();

            ddlDOBDay.Text = _profile.DOB.Day.ToString("00");
            ddlDOBMonth.Text = _profile.DOB.Month.ToString("00");
            ddlDOBYear.Text = _profile.DOB.Year.ToString("0000");

            _contact = _contactdb.GetContact(UserAccount.CEID);
            if (_contact != null)
            {
                string strMobile = _contact.Mobile;
                txtContactNumber.Text = strMobile;

                if (UserAccount.Status == true)
                {
                    txtEmailAddress.Text = _account.Email;
                }

                if (UserAccount.UserTypeId == 1001)
                {
                    txtEmailAddress.ReadOnly = false;
                }
                else
                {
                    txtEmailAddress.ReadOnly = _account.Status;
                }

            }

            _profile = null;
        }
    }

    protected void ddlBrokerProvider_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        LoadBrokerCoverType();

        ddlBrokerCoverType.Text = ddlInsuranceType.Text;

        if (Convert.ToInt64(txtCarId.Text) > 0)
        {
            lblQRefNo.Text = CE.Global.General.GetReferenceNumber(txtCarId.Text.Trim(), ddlBrokerProvider.Text.Trim());
        }
        else
        {
            lblQRefNo.Text = "NEW";
        }
        ddlBrokerCoverType_SelectedIndexChanged(sender, e);
    }

    private void LoadBrokerProvider()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", true);
        if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
        {
            ddlBrokerProvider.DataSource = _dtBrokerProvider;
            ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
            ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
            ddlBrokerProvider.DataBind();
        }

        ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
      
    }

    private void LoadBrokerCoverType()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        ddlBrokerCoverType.Items.Clear();
        
        MyDatabase _db = new MyDatabase();
        DataTable _dtBrokerCoverType = new DataTable("tblBrokerCoverType");
        _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 ORDER BY ProviderCoverTypeID");
        if (ddlBrokerProvider.Text == "41" && txtUserTypeId.Text == "1001")
        {
            _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 AND ProviderCoverTypeID<> 11 ORDER BY ProviderCoverTypeID");
        }
        if (_dtBrokerCoverType != null && _dtBrokerCoverType.Rows.Count > 0)
        {
            ddlBrokerCoverType.DataSource = _dtBrokerCoverType;
            ddlBrokerCoverType.DataTextField = _dtBrokerCoverType.Columns[1].ColumnName.ToString();
            ddlBrokerCoverType.DataValueField = _dtBrokerCoverType.Columns[0].ColumnName.ToString();
            ddlBrokerCoverType.DataBind();
        }
        

        ddlBrokerCoverType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));

       
    }

    protected void ddlBrokerCoverType_SelectedIndexChanged(object sender, EventArgs e)
    {
        

        if (ddlBrokerProvider.Text == "43" && (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11") && txtUserTypeId.Text == "1001")
        {
            ddlBrokerGarageType.Items.Clear();
            ddlBrokerGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
            ddlBrokerGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        else
        {
            ddlBrokerGarageType.Items.Clear();
            ddlBrokerGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
            ddlBrokerGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
            ddlBrokerGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }

        ddlBrokerGarageType.Text = ddlGarageType.Text;
        LoadDiscountPercentageList();
       
        LoadBrokerDefault(); //Sop Create method and updated on 16 Nov 2012 from BKK

    }

    protected void ddlDiscountPercentage_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
        if (ddlDiscountPercentage.Text == "0")
        {
            txtFinalAnnualPremiumNoDisc.Enabled = false;
        }
        else
        {
            txtFinalAnnualPremiumNoDisc.Enabled = true;
        }
    }

    protected void chkCompanyStaff_CheckedChanged(object sender, EventArgs e)
    {
        LoadDiscountPercentageList();

        if (chkCompanyStaff.Checked)
        {
            ListItem _lstTwelve = ddlDiscountPercentage.Items.FindByValue("12");
            if (_lstTwelve != null)
            {
                ddlDiscountPercentage.Text = "12";
            }
            ListItem _lstFifteen = ddlDiscountPercentage.Items.FindByValue("15");
            if (_lstFifteen != null)
            {
                ddlDiscountPercentage.Text = "15";
            }
            if (ddlBrokerProvider.Text == "41")
            {
                ddlDiscountPercentage.Text = "0";
            }
        }
       

        ddlDiscountPercentage_SelectedIndexChanged(sender, e);
    }

    private void LoadDiscountPercentageList()
    {
        int _maxPercentage = 0;
        int _providerComId = Convert.ToInt32(ddlBrokerProvider.Text);

        _maxPercentage = 10;

        if (chkCompanyStaff.Checked)
        {
            _maxPercentage = 15;
        }

        ddlDiscountPercentage.Items.Clear();

        for (int i = _maxPercentage; i >= 0; i--)
        {
            ddlDiscountPercentage.Items.Add(new ListItem(i.ToString() + " " + "%", i.ToString()));
        }

        ddlDiscountPercentage_SelectedIndexChanged(null, null);
    }

    protected void txtGrossPremium_TextChanged(object sender, EventArgs e)
    {
        try
        {
            
            decimal _premium = 0;
            txtVAT.Text = "";
            txtTax.Text = "";
            txtNetPremium.Text = "";
            txtAnnualPremium.Text = "";
            lblTax.Text = "0";
            lblVAT.Text = "0";
            lblNetPremium.Text = "0";
            lblAnnualPremium.Text = "0";

            if (decimal.TryParse(txtGrossPremium.Text, out _premium))
            {
                decimal _grossPremium = _premium;

                decimal _netPremium = _premium / 1.07M / 1.004M;

                _netPremium = Math.Floor(Math.Round(_netPremium));

                txtNetPremium.Text = _netPremium.ToString("#0.00");

                decimal _tax = 0;

                _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));

                _tax = Math.Ceiling(_tax);

                if (_tax >= 1000)
                {
                    lblTax.Text = _tax.ToString("#,000.00");
                }
                else
                {
                    lblTax.Text = _tax.ToString("#0.00");
                }

                txtTax.Text = _tax.ToString("#0.00");

                decimal _vat = 0;
                _vat = Convert.ToDecimal((_netPremium + _tax) * Convert.ToDecimal(7.0 / 100.0));

                if (_vat >= 1000)
                {
                    lblVAT.Text = _vat.ToString("#,000.00");
                }
                else
                {
                    lblVAT.Text = _vat.ToString("#0.00");
                }

                txtVAT.Text = _vat.ToString("#0.00");

                _netPremium = _grossPremium - (_vat + _tax);

                if (_netPremium >= 1000)
                {
                    lblNetPremium.Text = _netPremium.ToString("#,000.00");
                }
                else
                {
                    lblNetPremium.Text = _netPremium.ToString("#0.00");
                }

                decimal _annualPremium = 0;
                decimal _annualPremiumNoDisc = 0;

                _annualPremiumNoDisc = _netPremium + _vat + _tax;

                if (ddlDiscountPercentage.Text != "0" && Convert.ToInt32(ddlDiscountPercentage.Text) > 0)
                {
                    decimal _discountAmount = Convert.ToDecimal((_netPremium * Convert.ToDecimal(Convert.ToDecimal(ddlDiscountPercentage.Text) / 100.0M)));
                    if (_discountAmount >= 1000)
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#,000.00");
                    }
                    else
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#0.00");
                    }
                    _annualPremium = (_netPremium + _vat + _tax) - _discountAmount;
                }
                else
                {
                    lblDiscountAmount.Text = "0";
                    _annualPremium = _netPremium + _vat + _tax;
                }


                if (_annualPremium >= 1000)
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#,000.00");
                }
                else
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#0.00");
                }

                if (chkCTPL.Checked)
                {
                    _annualPremium = _annualPremium + Convert.ToDecimal(txtCTPL.Text);
                    _annualPremiumNoDisc = _annualPremiumNoDisc + Convert.ToDecimal(txtCTPL.Text);
                }

                txtAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremiumNoDisc.Text = _annualPremiumNoDisc.ToString("#0.00");
            }
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    private void LoadBrokerDefault() //Sop Create method and updated on 16 Nov 2012 from BKK
    {
        try
        {
            MyDatabase _myDB = new MyDatabase();

            string _strSelect = "Select * from tblCXBrokerDefaultBenefits ";
            _strSelect = _strSelect + " WHERE CXBrokerProviderId = " + ddlBrokerProvider.Text;
            _strSelect = _strSelect + " AND GarageType = " + ddlGarageType.Text;
            _strSelect = _strSelect + " AND InsuranceType = " + ddlBrokerCoverType.SelectedValue;

            DataTable _dtDefaultValues = new DataTable("tblDefault");

            _dtDefaultValues = _myDB.GetDataTable(_strSelect);

            if (_dtDefaultValues != null && _dtDefaultValues.Rows.Count > 0)
            {
                if (_dtDefaultValues.Rows[0]["TPBIA"] != DBNull.Value)
                {
                    txtTPBIA.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                }

                if (_dtDefaultValues.Rows[0]["TPBIP"] != DBNull.Value)
                {
                    txtTPBIP.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                }

                if (_dtDefaultValues.Rows[0]["TPPD"] != DBNull.Value)
                {
                    txtTPPD.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPPD"].ToString()).ToString("#,000");
                }

                if (_dtDefaultValues.Rows[0]["PAPassenger"] != DBNull.Value)
                {
                    txtPA.Text = _dtDefaultValues.Rows[0]["PAPassenger"].ToString();
                }

                if (_dtDefaultValues.Rows[0]["MedicalExpense"] != DBNull.Value)
                {
                    txtMED.Text = _dtDefaultValues.Rows[0]["MedicalExpense"].ToString();
                }

                if (_dtDefaultValues.Rows[0]["BailBond"] != DBNull.Value)
                {
                    txtBailBond.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["BailBond"].ToString()).ToString("#,000");
                }


                if (_dtDefaultValues.Rows[0]["DEC"] != DBNull.Value)
                {
                    txtDeductible.Text = _dtDefaultValues.Rows[0]["DEC"].ToString();
                }
                if (_dtDefaultValues.Rows[0]["FireTheft"] != DBNull.Value)
                {
                    txtFireTheft.Text = _dtDefaultValues.Rows[0]["FireTheft"].ToString();
                }
                if (_dtDefaultValues.Rows[0]["FloodCover"] != DBNull.Value)
                {
                    txtFloodCoverAmount.Text = _dtDefaultValues.Rows[0]["FloodCover"].ToString();
                }
            }
        }
        catch (Exception Ex)
        {
            lblPremiumMessage.Text = Ex.Message;
        }
    }

    protected void ddlVehicleBodyType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleBodyType.Text == "1")
        {
            txtCTPL.Text = "645.21";
        }
        else if (ddlVehicleBodyType.Text == "2")
        {
            txtCTPL.Text = "967.28";
        }
        else
        {
            txtCTPL.Text = "0";
        }

        txtGrossPremium_TextChanged(sender, e);
    }

    protected void txtCTPL_TextChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
    }

    protected void chkCTPL_CheckedChanged(object sender, EventArgs e)
    {
        

        if (chkCTPL.Checked)
        {
            txtCTPL.Enabled = true;
            ddlVehicleBodyType.Enabled = true;
            ddlVehicleBodyType_SelectedIndexChanged(sender, e);
        }
        else
        {
            txtCTPL.Enabled = false;
            ddlVehicleBodyType.Enabled = false;
            txtGrossPremium_TextChanged(sender, e);
        }
    }

    protected void chkChangePremium_CheckedChanged(object sender, EventArgs e)
    {
        rfvPremiumChangeComments.Enabled = chkChangePremium.Checked;
        txtFinalAnnualPremiumNoDisc.ReadOnly = !chkChangePremium.Checked;
        txtFinalAnnualPremium.ReadOnly = !chkChangePremium.Checked;
    }

    protected Int64 SavePremium()
    {
        float _sumInsured = 0.0f;

        if (!float.TryParse(txtOwnDamage.Text, out _sumInsured))
        {
            lblPremiumError.Text = Resources.General.SumInsurredNotValid;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.SumInsurredNotValid + "');", true);
            return -1;
        }


        

        Int64 _result = 0;
        string _ProductType = "CIN";
        BrokerPremium _brokerPremium = new BrokerPremium();
        BrokerPremiumDB _brokerPremiumdb = new BrokerPremiumDB();


        _brokerPremium.CXBrokerPremiumId = Convert.ToInt64(txtPremiumId.Text);
        _brokerPremium.CXBrokerProviderId = Convert.ToInt64(ddlBrokerProvider.Text);
        _brokerPremium.ProviderCoverTypeId = Convert.ToInt64(ddlBrokerCoverType.Text);
        _brokerPremium.CECarId = Convert.ToInt64(txtCarId.Text);
        _brokerPremium.CustomerId = Convert.ToInt64(txtCustomerId.Text);
        _brokerPremium.AgentId = Convert.ToInt64(Session[General.UserId].ToString());
        _brokerPremium.Premium = Convert.ToSingle(txtNetPremium.Text);

        _brokerPremium.SelectedStatus = chkSelected.Checked;
        _brokerPremium.WorkShop = ddlGarageType.Text;
        _brokerPremium.ProductType = _ProductType;
        _brokerPremium.TotalVMI = Convert.ToSingle(txtGrossPremium.Text);

        _brokerPremium.IsIncludeCMI = chkCTPL.Checked;

        if (chkCTPL.Checked)
        {
            _brokerPremium.TotalCMI = Convert.ToSingle(txtCTPL.Text);
        }
        else
        {
            _brokerPremium.TotalCMI = 0;
        }
        _brokerPremium.DiscountPercentage = Convert.ToInt16(ddlDiscountPercentage.Text);


        _brokerPremium.SumInsured = Convert.ToInt32(_sumInsured.ToString("#0"));
        if (_sumInsured > 1000)
        {
            _brokerPremium.OwnDamage = _sumInsured.ToString("#,000");
        }
        else
        {
            _brokerPremium.OwnDamage = _sumInsured.ToString("#0");
        }

        _brokerPremium.AnnualPremium = Convert.ToSingle(txtAnnualPremium.Text);
        _brokerPremium.TPPD = txtTPPD.Text;
        _brokerPremium.TPBIP = txtTPBIP.Text;
        _brokerPremium.TPBIA = txtTPBIA.Text;
        _brokerPremium.DEC = txtDeductible.Text;
        _brokerPremium.FireTheft = txtFireTheft.Text;

        _brokerPremium.PADriver = txtPA.Text;
        _brokerPremium.MedicalExpense = txtMED.Text;
        _brokerPremium.BailBound = txtBailBond.Text;

        _brokerPremium.Info1 = lblQRefNo.Text;
        _brokerPremium.Info2 = txtEditLicensePlate.Text;
        _brokerPremium.Info3 = ddlVehicleBodyType.Text;
        _brokerPremium.Info4 = chkCompanyStaff.Checked ? "1" : "0";
        _brokerPremium.Info5 = txtFloodCoverAmount.Text;
        _brokerPremium.Info6 = ddlNamedDriver.Text == "0" ? "0" : "1";
        _brokerPremium.Info7 = txtAccModCost.Text;
        _brokerPremium.Info8 = txtPremiumChangeComments.Text;

        

        _brokerPremium.PaymentOption = "FP";
        _brokerPremium.FinalAnnualPremium = Convert.ToSingle(txtFinalAnnualPremium.Text);
        _brokerPremium.FinalAnnualPremiumNoDisc = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);

        

        _result = _brokerPremiumdb.Insert(_brokerPremium);
        if (_result > 0)
        {
            txtPremiumId.Text = _result.ToString();
        }
        return _result;
    }

    protected void csvDeductibleValid_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        float _deductible = 0.0f;
        if (ddlBrokerProvider.Text == "43" && ddlBrokerCoverType.Text == "31" && txtUserTypeId.Text == "1001")
        {
            if (txtDeductible.Text.Trim() != "")
            {
                if (!float.TryParse(txtDeductible.Text, out _deductible))
                {
                    _deductible = 0.0f;
                }
                if (_deductible > 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
            else
            {
                args.IsValid = false;
            }
        }
    }

    protected void ddlNamedDriver_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt16(ddlNamedDriver.Text) == 0)
        {
            rfvDriver1DOBDay.Enabled = false;
            rfvDriver1DOBMonth.Enabled = false;
            rfvDriver1DOBYear.Enabled = false;
            rfvDriver2DOBDay.Enabled = false;
            rfvDriver2DOBMonth.Enabled = false;
            rfvDriver2DOBYear.Enabled = false;

            rfvDriverFirst.Enabled = false;
            revDriverFirst.Enabled = false;
            rfvDriver1IDNo.Enabled = false;
            rfvDriver1LicenseNo.Enabled = false;
            rfvDriverTwo.Enabled = false;
            revDriverTwo.Enabled = false;
            rfvDriver2IDNo.Enabled = false;
            rfvDriver2LicenseNo.Enabled = false;

            ddlDriver1DOBDay.Enabled = false;
            ddlDriver1DOBMonth.Enabled = false;
            ddlDriver1DOBYear.Enabled = false;
            txtDriverFirst.Enabled = false;
            txtDriver1IDNo.Enabled = false;
            txtDriver1LicenseNo.Enabled = false;
            ddlDriver2DOBDay.Enabled = false;
            ddlDriver2DOBMonth.Enabled = false;
            ddlDriver2DOBYear.Enabled = false;
            txtDriverTwo.Enabled = false;
            txtDriver2IDNo.Enabled = false;
            txtDriver2LicenseNo.Enabled = false;
        }
        else if (Convert.ToInt16(ddlNamedDriver.Text) == 1)
        {
            rfvDriver1DOBDay.Enabled = true;
            rfvDriver1DOBMonth.Enabled = true;
            rfvDriver1DOBYear.Enabled = true;
            rfvDriver2DOBDay.Enabled = false;
            rfvDriver2DOBMonth.Enabled = false;
            rfvDriver2DOBYear.Enabled = false;

            rfvDriverFirst.Enabled = true;
            revDriverFirst.Enabled = true;
            rfvDriver1IDNo.Enabled = true;
            rfvDriver1LicenseNo.Enabled = true;
            rfvDriverTwo.Enabled = false;
            revDriverTwo.Enabled = false;
            rfvDriver2IDNo.Enabled = false;
            rfvDriver2LicenseNo.Enabled = false;

            ddlDriver1DOBDay.Enabled = true;
            ddlDriver1DOBMonth.Enabled = true;
            ddlDriver1DOBYear.Enabled = true;
            txtDriverFirst.Enabled = true;
            txtDriver1IDNo.Enabled = true;
            txtDriver1LicenseNo.Enabled = true;
            ddlDriver2DOBDay.Enabled = false;
            ddlDriver2DOBMonth.Enabled = false;
            ddlDriver2DOBYear.Enabled = false;
            txtDriverTwo.Enabled = false;
            txtDriver2IDNo.Enabled = false;
            txtDriver2LicenseNo.Enabled = false;
        }
        else if (Convert.ToInt16(ddlNamedDriver.Text) == 2)
        {
            rfvDriver1DOBDay.Enabled = true;
            rfvDriver1DOBMonth.Enabled = true;
            rfvDriver1DOBYear.Enabled = true;
            rfvDriver2DOBDay.Enabled = true;
            rfvDriver2DOBMonth.Enabled = true;
            rfvDriver2DOBYear.Enabled = true;

            rfvDriverFirst.Enabled = true;
            revDriverFirst.Enabled = true;
            rfvDriver1IDNo.Enabled = true;
            rfvDriver1LicenseNo.Enabled = true;
            rfvDriverTwo.Enabled = true;
            revDriverTwo.Enabled = true;
            rfvDriver2IDNo.Enabled = true;
            rfvDriver2LicenseNo.Enabled = true;

            ddlDriver1DOBDay.Enabled = true;
            ddlDriver1DOBMonth.Enabled = true;
            ddlDriver1DOBYear.Enabled = true;
            txtDriverFirst.Enabled = true;
            txtDriver1IDNo.Enabled = true;
            txtDriver1LicenseNo.Enabled = true;
            ddlDriver2DOBDay.Enabled = true;
            ddlDriver2DOBMonth.Enabled = true;
            ddlDriver2DOBYear.Enabled = true;
            txtDriverTwo.Enabled = true;
            txtDriver2IDNo.Enabled = true;
            txtDriver2LicenseNo.Enabled = true;
        }
        lblLoadMessage.Text = string.Empty;
    }

    protected Int64 SaveAppDetail()
    {
        lblLoadMessage.Text = string.Empty;
        Int64 _result = -1;
        Int64 _AgentId = 0;
        Int64 _AdminId = 0;

        NonGGPackage _nonggpackage = new NonGGPackage();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        _nonggpackage.CECarId = Convert.ToInt64(txtCarId.Text);
        _nonggpackage.ProviderCompanyId = Convert.ToInt64(ddlBrokerProvider.Text);
        _nonggpackage.Title = Server.HtmlEncode(txtPrefix.Text);
        _nonggpackage.CustomerType = ddlCustomerType.Text;
        _nonggpackage.CustomerName = Server.HtmlEncode(txtCustomerName.Text);
        _nonggpackage.Name = Server.HtmlEncode(txtInsuredPerson.Text);
        DateTime _dtDOB = new DateTime(Convert.ToInt32(ddlDOBYear.Text), Convert.ToInt32(ddlDOBMonth.Text), Convert.ToInt32(ddlDOBDay.Text));
        _nonggpackage.DOB = _dtDOB;
        _nonggpackage.Gender = ddlGender.Text;
        _nonggpackage.Occupation = Convert.ToInt32(ddlOccupation.Text);
        _nonggpackage.ContactNo = Server.HtmlEncode(txtContactNumber.Text);
        _nonggpackage.PresentAddress = Server.HtmlEncode(txtCurrentAddress.Text);
        _nonggpackage.SubDistrict = Server.HtmlEncode(txtSubDistrict.Text);
        _nonggpackage.District = Server.HtmlEncode(txtStateProvince.Text);
        _nonggpackage.Province = Server.HtmlEncode(txtProvince.Text);
        _nonggpackage.PostalCode = txtPostalCode.Text;
        _nonggpackage.Package = Server.HtmlEncode(txtPackage.Text);
        _nonggpackage.NoOfDriver = Convert.ToInt16(ddlNamedDriver.Text);
        _nonggpackage.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
        _nonggpackage.GarageType = Convert.ToInt32(ddlGarageType.Text);
        _nonggpackage.CarYear = Convert.ToInt32(ddlCarYear.Text);
        _nonggpackage.CarModel = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
       
        _nonggpackage.Beneficiary = Server.HtmlEncode(txtBeneficiary.Text);
        _nonggpackage.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
      
        Int32 _outSumInsurred = 0;
        if (!Int32.TryParse(txtSumInsured.Text, out _outSumInsurred))
        {
            _outSumInsurred = 0;
        }
        _nonggpackage.SumInsured = _outSumInsurred;
        _nonggpackage.NCB = Convert.ToInt32(ddlNCB.Text);
        _nonggpackage.CurrentInsurer = ddlCurrentInsurer.SelectedItem.Text;
        _nonggpackage.CarPlate = Server.HtmlEncode(txtEditLicensePlate.Text);
        _nonggpackage.CarPlateProvince = Server.HtmlEncode(txtRegistrationProvince.Text);
        _nonggpackage.EngineNumber = Server.HtmlEncode(txtEngineNumber.Text);
        _nonggpackage.ChassisNumber = Server.HtmlEncode(txtChassisNumber.Text);
       
        DateTime _dtCommDate = new DateTime(Convert.ToInt32(ddlCommenceYear.Text), Convert.ToInt32(ddlCommenceMonth.Text), Convert.ToInt32(ddlCommenceDay.Text));
        _nonggpackage.CoverageStart = _dtCommDate;
        DateTime _dtPolicyDate = new DateTime(Convert.ToInt32(ddlPolicyYear.Text), Convert.ToInt32(ddlPolicyMonth.Text), Convert.ToInt32(ddlPolicyDay.Text));
        _nonggpackage.CTPLStart = _dtPolicyDate;

        _nonggpackage.Premium = Convert.ToSingle(txtNetPremium.Text);
        _nonggpackage.IsCTPL = chkCTPL.Checked;
        _nonggpackage.CTPL = Convert.ToSingle(txtCTPL.Text);

        _nonggpackage.TotalCollectedPremium = Convert.ToSingle(txtFinalAnnualPremium.Text);
        _nonggpackage.TotalPremium = Convert.ToSingle(txtGrossPremium.Text);
        _nonggpackage.TermPremium = Convert.ToSingle(txtGrossPremium.Text);
       
        _nonggpackage.QuoteRefNo = lblQRefNo.Text;
        _nonggpackage.Status = true;
        _nonggpackage.RefCEUserId = Convert.ToInt64(txtCustomerId.Text);

        if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "100")
        {
            _nonggpackage.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
            _nonggpackage.AdminId = _AdminId;
        }
        else
        {
            if (_AgentId == 0)
            {
                _nonggpackage.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
            }
            else
            {
                _nonggpackage.AgentId = _AgentId;
            }

            _nonggpackage.AdminId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
        }

        _nonggpackage.Info1 = "NEW";

      


        _nonggpackage.IsCreditCardOwner = 1;


        _nonggpackage.Info4 = Server.HtmlEncode(txtAccModCost.Text.Trim());
        _nonggpackage.Info4 = "0";

        _result = _nonggpackagedb.Insert(_nonggpackage);
        Int32 driverresult = 0;
        if (_result > 0)
        {
            if (Convert.ToInt16(ddlNamedDriver.Text) > 0)
            {
                if (SaveDriverDetails())
                {
                    driverresult = 1;
                }
                else
                {
                    driverresult = 0;
                }
            }
            else
            {
                driverresult = 1;
            }
            if (driverresult > 0)
            {
                string _fileName = lblQRefNo.Text.Trim() + "_" + dateTimeNow.Day.ToString("00") + "-" + dateTimeNow.Month.ToString("00") + "-" + dateTimeNow.Year;
                string _filePath = GetExcelFilePath(Convert.ToInt64(ddlBrokerProvider.Text), lblQRefNo.Text.Trim());
                string ExcelFile = GenerateNonGGExcel(_nonggpackage.CECarId, _nonggpackage.ProviderCompanyId, _filePath, _fileName);
                if (ExcelFile != null)
                {
                    Int64 _excelResult = -1;
                    _excelResult = _nonggpackagedb.UpdateExcelName(_nonggpackage.CECarId, ExcelFile);
                }
            }
        }
        return _result;
    }

    private string GetExcelFilePath(Int64 ProviderCompanyId, string QuoteRefNo)
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        string _provider = CE.Global.General.GetProvider(ProviderCompanyId);
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _currentMonth = dateTimeNow.ToString("yyyyMMM");
        string _todaydate = dateTimeNow.ToString("yyyyMMMdd");
        _filePath += "exceloutput\\" + _provider + "\\";
        if (!_myIO.CheckDirectory(_filePath + _currentMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _currentMonth))
            {
                _filePath += _currentMonth + "\\";
            }
        }
        else
        {
            _filePath += _currentMonth + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + QuoteRefNo))
        {
            if (_myIO.CreateDirectory(_filePath, QuoteRefNo))
            {
                _filePath += QuoteRefNo + "\\";
            }
        }
        else
        {
            _filePath += QuoteRefNo + "\\";
        }
        return _filePath;
    }

    private bool SaveDriverDetails()
    {
        bool _result = false;
        NonGGCarDriver _nonggcardriver = new NonGGCarDriver();
        NonGGCarDriverDB _nonggcardriverdb = new NonGGCarDriverDB();

        if (ddlNamedDriver.Text != "0")
        {
            int _drivercount = Convert.ToInt32(ddlNamedDriver.Text);
            int _insertcount = 0;

            for (int i = 1; i <= _drivercount; i++)
            {
                if (Session[CE.Global.General.UserId] != null)
                {
                    _nonggcardriver.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }
                else
                {
                    _nonggcardriver.AgentId = 0;
                }
                _nonggcardriver.RefCEUserId = Convert.ToInt64(txtCustomerId.Text);
                _nonggcardriver.CECarId = Convert.ToInt64(txtCarId.Text);
                if (i == 1)
                {
                    _nonggcardriver.CarDriverId = Convert.ToUInt32(txtDriverId1.Text);
                    _nonggcardriver.FullName = Server.HtmlEncode(txtDriverFirst.Text.Trim());
                    DateTime _dtDriver1DOB = new DateTime(Convert.ToInt32(ddlDriver1DOBYear.Text), Convert.ToInt32(ddlDriver1DOBMonth.Text), Convert.ToInt32(ddlDriver1DOBDay.Text));
                    _nonggcardriver.DOB = _dtDriver1DOB;
                    _nonggcardriver.IDNo = Server.HtmlEncode(txtDriver1IDNo.Text.Trim());
                    _nonggcardriver.DrivingLicenseNumber = Server.HtmlEncode(txtDriver1LicenseNo.Text.Trim());
                    _nonggcardriver.Status = true;
                }
                else if (i == 2)
                {
                    _nonggcardriver.CarDriverId = Convert.ToUInt32(txtDriverId2.Text); ;
                    _nonggcardriver.FullName = Server.HtmlEncode(txtDriverTwo.Text.Trim());
                    DateTime _dtDriver2DOB = new DateTime(Convert.ToInt32(ddlDriver2DOBYear.Text), Convert.ToInt32(ddlDriver2DOBMonth.Text), Convert.ToInt32(ddlDriver2DOBDay.Text));
                    _nonggcardriver.DOB = _dtDriver2DOB;
                    _nonggcardriver.IDNo = Server.HtmlEncode(txtDriver2IDNo.Text.Trim());
                    _nonggcardriver.DrivingLicenseNumber = Server.HtmlEncode(txtDriver2LicenseNo.Text.Trim());
                    _nonggcardriver.Status = true;
                }
                if (_nonggcardriverdb.Insert(_nonggcardriver) > 0)
                {
                    _insertcount++;
                    _result = true;
                }
            }
            _nonggcardriverdb = null;
            _nonggcardriver = null;
        }
        return _result;
    }

    public string GenerateNonGGExcel(Int64 CECarId, Int64 ProviderId, string FilePath, string FileName)
    {
        string _returnFilePath = "";
        Label lblContent = new Label();
        StringBuilder strText = new StringBuilder("");
        strText.Append("<table><tr><td colspan='2'><h3>ประกันภัยรถยนต์ - แบบฟอร์ม</h3></td></tr></table>");
        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        _dsApplication = _nonggpackagedb.GetNonGGApplication(CECarId, ProviderId, 0);
        string _html = "";
        if (_dsApplication.Tables[0].Rows.Count > 0)
        {

            #region Variable Declaration

           
            MyDatabase _db = new MyDatabase();
            string Title, Name, DOB, Gender, Occupation, ContactNo, Email, PresentAddress, SubDistrict, District, Province, PostalCode, Insurer, Package, NoOfDriver;
            string InsuranceType, GarageType, CarModelYear, CarMakeModel, Size, VehicleWeight, NumberofSeat, Beneficiary, VehicleType, SumInsured, NCB;
            string CurrentInsurer, CarPlate, CarPlateProvince, EngineNumber, ChassisNumber, Modification, AnyClaims, AddDrivers, CommencementDate;
            string Premium, CTPL, CTPLAmount, TotalPremium, PaymentType, QuoteRefNo, Payment, ApplicationDate, TotalCollectedPremium, CustomerName;
            string CustomerType, CTPLStart, ProviderPremium, strLastYearRefNo, strLastYearPolicyNo, strTitle, ModificationAmount;
           
            float _GrossPremium = 0.0f;

            strLastYearRefNo = string.Empty;
            strLastYearPolicyNo = string.Empty;
            Title = ""; Name = ""; DOB = ""; Gender = ""; Occupation = ""; ContactNo = ""; Email = ""; PresentAddress = ""; SubDistrict = ""; District = "";
            Province = ""; PostalCode = ""; Insurer = ""; Package = ""; NoOfDriver = ""; InsuranceType = ""; GarageType = ""; CarModelYear = "";
            CarMakeModel = ""; Size = ""; VehicleWeight = ""; NumberofSeat = ""; Beneficiary = ""; VehicleType = ""; SumInsured = ""; NCB = "";
            CurrentInsurer = ""; CarPlate = ""; CarPlateProvince = ""; EngineNumber = ""; ChassisNumber = ""; Modification = ""; AnyClaims = "";
            AddDrivers = ""; CommencementDate = ""; Premium = ""; CTPL = ""; CTPLAmount = ""; TotalPremium = ""; PaymentType = ""; CTPLStart = "";
            QuoteRefNo = ""; Payment = ""; ApplicationDate = ""; TotalCollectedPremium = ""; CustomerName = ""; CustomerType = ""; ProviderPremium = "";
            ModificationAmount = string.Empty;
            //For Driver
            string DriverName1, DriverDOB1, DriverName2, DriverDOB2, Driver1LicenseNo, Driver2LicenseNo, Driver1IDNo, Driver2IDNo;
            DriverName1 = ""; DriverDOB1 = ""; DriverName2 = ""; DriverDOB2 = ""; Driver1LicenseNo = ""; Driver2LicenseNo = "";
            Driver1IDNo = ""; Driver2IDNo = "";

            #endregion

            #region Assign Values
            strTitle = "รายละเอียดผู้ทำประกัน";

            Email = _dsApplication.Tables[0].Rows[0]["Email"].ToString();
            Title = _dsApplication.Tables[0].Rows[0]["Title"].ToString();
            Name = _dsApplication.Tables[0].Rows[0]["Name"].ToString();
            CustomerName = _dsApplication.Tables[0].Rows[0]["CustomerName"].ToString();
            CustomerType = _dsApplication.Tables[0].Rows[0]["CustomerTypeTH"].ToString();
            DOB = _dsApplication.Tables[0].Rows[0]["DOB"].ToString();
            Gender = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
            Occupation = _dsApplication.Tables[0].Rows[0]["Occupation"].ToString();
            ContactNo = _dsApplication.Tables[0].Rows[0]["ContactNo"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            PresentAddress = _dsApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
            SubDistrict = _dsApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
            District = _dsApplication.Tables[0].Rows[0]["District"].ToString();
            Province = _dsApplication.Tables[0].Rows[0]["Province"].ToString();
            PostalCode = _dsApplication.Tables[0].Rows[0]["PostalCode"].ToString();
            Insurer = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
            Package = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
            NoOfDriver = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
            if (NoOfDriver.ToString() == "0")
            {
                AddDrivers = "No";
            }
            else
            {
                AddDrivers = "Yes";
            }
            InsuranceType = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
            GarageType = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
            CarModelYear = _dsApplication.Tables[0].Rows[0]["CarModelYear"].ToString();
            CarMakeModel = _dsApplication.Tables[0].Rows[0]["CarMakeModel"].ToString();
          
            EngineNumber = _dsApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
            ChassisNumber = _dsApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            VehicleType = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
            SumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
            NCB = _dsApplication.Tables[0].Rows[0]["NCB"].ToString();
            CurrentInsurer = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
            CarPlate = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();
            CarPlateProvince = _dsApplication.Tables[0].Rows[0]["ProvinceRegistration"].ToString();
           
            CommencementDate = _dsApplication.Tables[0].Rows[0]["CommencementDate"].ToString();
            Premium = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();

            CTPL = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
            CTPLAmount = _dsApplication.Tables[0].Rows[0]["CTPLAmount"].ToString();
            CTPLStart = _dsApplication.Tables[0].Rows[0]["CTPLStart"].ToString();
            TotalPremium = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
            TotalCollectedPremium = _dsApplication.Tables[0].Rows[0]["TotalCollectedPremium"].ToString();
            PaymentType = _dsApplication.Tables[0].Rows[0]["PaymentType"].ToString();
            QuoteRefNo = _dsApplication.Tables[0].Rows[0]["QuoteRefNo"].ToString();
            Payment = _dsApplication.Tables[0].Rows[0]["Payment"].ToString();
            ApplicationDate = _dsApplication.Tables[0].Rows[0]["ApplicationDate"].ToString();
           
            if (_dsApplication.Tables[0].Rows[0]["GrossPremium"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["GrossPremium"].ToString() != string.Empty)
            {
                _GrossPremium = Convert.ToSingle(_dsApplication.Tables[0].Rows[0]["GrossPremium"].ToString());
            }

            ProviderPremium = GetProviderPremium(_GrossPremium, CTPL.ToUpper(), CTPLAmount);

            if (_dsApplication.Tables[0].Rows[0]["ModificationAmount"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString() != string.Empty)
            {
                ModificationAmount = _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString();
            }

            if (AddDrivers == "Yes")
            {
                if (_dsApplication.Tables[1].Rows.Count > 0)
                {
                    if (Convert.ToInt16(NoOfDriver) > 0)
                    {
                        DriverName1 = _dsApplication.Tables[1].Rows[0]["FullName"].ToString();
                        DriverDOB1 = _dsApplication.Tables[1].Rows[0]["DOB"].ToString();
                        Driver1IDNo = _dsApplication.Tables[1].Rows[0]["IDNo"].ToString();
                        Driver1LicenseNo = _dsApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
                    }
                    if (Convert.ToInt16(NoOfDriver) > 1)
                    {

                        DriverName2 = _dsApplication.Tables[1].Rows[1]["FullName"].ToString();
                        DriverDOB2 = _dsApplication.Tables[1].Rows[1]["DOB"].ToString();
                        Driver2IDNo = _dsApplication.Tables[1].Rows[1]["IDNo"].ToString();
                        Driver2LicenseNo = _dsApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
                    }
                }
            }

            #endregion

            #region Generate Excel File
            _html += "<html><body><table width='60%' cellpadding='1' cellspacing='1' border='1'>";
            

            _html += "<tr><td width='20%' align='left' colspan='2'><b>รายละเอียดผู้ทำประกัน</b></td></tr>";

            _html += "<tr><td width='300' align='left'><b>ประเภทลูกค้า</b></td><td  align='left'>" + CustomerType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>คำนำหน้า</b></td><td  align='left'>" + Title + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ชื่อผู้ทำประกัน</b></td><td  align='left'>" + Name + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>วันเกิด</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + DOB + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เพศ</b></td><td  align='left'>" + Gender + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>อาชีพ</b></td><td  align='left'>" + Occupation + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบอร์ติดต่อ</b></td><td style='mso-number-format:\\@' align='left'>" + ContactNo + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ที่อยู่ปัจจุบัน</b></td><td  align='left'>" + PresentAddress + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>แขวง/ตำบล</b></td><td  align='left'>" + SubDistrict + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เขต/อำเภอ</b></td><td  align='left'>" + District + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จังหวัด</b></td><td  align='left'>" + Province + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>รหัสไปรษณีย์</b></td><td  align='left'>" + PostalCode + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>บริษัทประกัน</b></td><td  align='left'>" + Insurer + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>แพกเก็จ</b></td><td  align='left'>" + Package + "</td></tr>";

            _html += "<tr><td width='300' align='left'><b>ระบุผู้ขับขี่</b></td><td  align='left'>" + AddDrivers + "</td></tr>";
            if (AddDrivers == "Yes")
            {
                _html += "<tr><td width='300' align='left'><b>จำนวนผู้ขับขี่</b></td><td  align='left'>" + NoOfDriver + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 0)
            {
                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 1</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB1 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1</b></td><td  align='left'>" + DriverName1 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver1IDNo + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่ใบขับขี่</b></td><td  align='left'>" + Driver1LicenseNo + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 1)
            {
                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 2</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB2 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2</b></td><td  align='left'>" + DriverName2 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver2IDNo + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่ใบขับข</b></td><td  align='left'>" + Driver2LicenseNo + "</td></tr>";
            }
            _html += "<tr><td width='300' align='left'><b>ประเภทประกัน</b></td><td  align='left'>" + InsuranceType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ประเภทอู่</b></td><td  align='left'>" + GarageType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ปีของรถ</b></td><td  align='left'>" + CarModelYear + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>รุ่น</b></td><td  align='left'>" + CarMakeModel + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ผู้รับผลประโยชน์</b></td><td  align='left'>" + Beneficiary + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ประเภทรถ</b></td><td  align='left'>" + VehicleType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ทุนประกัน</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + SumInsured + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ส่วนลด NCB</b></td><td  align='left'>" + NCB + "</td></tr>";
            if (ModificationAmount.ToString() != string.Empty && ModificationAmount.ToString() != "")
            {
                _html += "<tr><td width='300' align='left'><b>อุปกรณ์หรือการปรับเปลี่ยนค่าใช้จ่าย</b></td><td  align='left'>" + ModificationAmount + "</td></tr>";
            }
            _html += "<tr><td width='300' align='left'><b>บริษัทประกันปัจจุบัน</b></td><td  align='left'>" + CurrentInsurer + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ทะเบียนรถ</b></td><td  align='left'>" + CarPlate + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จังหวัดที่จดทะเบียน</b></td><td  align='left'>" + CarPlateProvince + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>หมายเลขเครื่อง</b></td><td  align='left'>" + EngineNumber + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>หมายเลข Chassis</b></td><td  align='left'>" + ChassisNumber + "</td></tr>";
            _html += "<tr><td width='300'  align='left'><b>วันเริ่มคุ้มครอง (ภาคสมัครใจ)</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CommencementDate + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบี้ยประกันภาคสมัครใจ</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + _GrossPremium.ToString() + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ซื้อ พ.ร.บ. หรือไม่</b></td><td  align='left'>" + CTPL + "</td></tr>";
            if (CTPL == "Yes")
            {
                _html += "<tr><td width='300' align='left'><b>เบี้ย พ.ร.บ.</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + CTPLAmount + "</td></tr>";
            }
            else
            {
                _html += "<tr><td width='300' align='left'><b>เบี้ย พ.ร.บ.</b></td><td align='left'>-</td></tr>";
            }
            _html += "<tr><td width='300'  align='left'><b>วันที่ พ.ร.บ.เริ่มคุ้มครอง</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CTPLStart + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบี้ยประกันรวมทั้งหมด</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + ProviderPremium + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>วันที่ทำรายการ</b></td><td align='left'>ตาม วัน/เวลา ที่ปรากฎในอีเมล์</td></tr>";

            _html += "</table></body></html>";
            #endregion

            lblContent.Text = _html;
            MyIO myio = new MyIO();

            string[] filecontent = new string[1];
            filecontent[0] = lblContent.Text.ToString();

            myio.WriteNewFile(FilePath, FileName + ".xls", filecontent);
            _returnFilePath = FilePath + FileName + ".xls";
        }
        return _returnFilePath;
    }

    private string GetProviderPremium(float GrossPremium, string CTPL, string CTPLAmount)
    {
        string _retValue = string.Empty;
        try
        {
            if (CTPL.ToString() == string.Empty)
            {
                CTPL = "NO";
            }
            if (CTPLAmount.ToString() == string.Empty)
            {
                CTPLAmount = "0";
            }
            decimal _grossPremium = Convert.ToDecimal(GrossPremium.ToString());
            if (CTPL == "YES")
            {
                _grossPremium = _grossPremium + Convert.ToDecimal(CTPLAmount.ToString());
            }
            _retValue = _grossPremium.ToString("#.00");
        }
        catch (Exception Ex)
        {
            Ex = null;
        }

        return _retValue;
    }

    public void LoadApplicationDetails()
    {
        

        DataSet _dsApplication = new DataSet();
        NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
        
        _dsApplication = _nonggpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtCustomerId.Text.Trim()));
        if (_dsApplication != null && _dsApplication.Tables.Count > 0 && _dsApplication.Tables[0].Rows.Count > 0)
        {
            txtUserTypeId.Text = _dsApplication.Tables[0].Rows[0]["UsrTypeId"].ToString();

            if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
            {
                LoadNonGGApplicationDetails(_dsApplication);
            }
            else if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count == 0)
            {
                #region Assign Values
                ddlCustomerType.SelectedIndex = 0;

               

                if (_dsApplication != null && _dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                {
                    if (_dsApplication.Tables[4].Rows[0]["Name"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["Name"].ToString() != string.Empty)
                    {
                        txtCustomerName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                    }
                    else
                    {
                        txtCustomerName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    }
                }
                else
                {
                    txtCustomerName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                }

               
                txtInsuredPerson.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                txtContactNumber.Text = _dsApplication.Tables[0].Rows[0]["Mobile"].ToString();
               
                txtPackage.Text = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
                ddlNamedDriver.Text = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
                ddlNamedDriver_SelectedIndexChanged(null, null);
                txtDriverId1.Text = "0";
                txtDriverId2.Text = "0";
                DateTime Commdate = dateTimeNow;
                if (_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                {
                    Commdate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString());
                }
              

                ddlCommenceDay.Text = Commdate.Day.ToString("00");
                ddlCommenceMonth.Text = Commdate.Month.ToString("00");
                ddlCommenceYear.Text = Commdate.Year.ToString("0000");

               

                ddlPolicyDay.Text = Commdate.Day.ToString("00");
                ddlPolicyMonth.Text = Commdate.Month.ToString("00");
                ddlPolicyYear.Text = Commdate.Year.ToString("0000");

               

                DateTime DriverDOB1 = dateTimeNow.AddYears(-20);
                DateTime DriverDOB2 = dateTimeNow.AddYears(-20);
                if (_dsApplication.Tables.Count > 1)
                {
                    if (_dsApplication.Tables[1].Rows.Count > 0 && _dsApplication.Tables[1].Rows[0]["DOB"] != DBNull.Value && _dsApplication.Tables[1].Rows[0]["DOB"].ToString() != string.Empty)
                    {
                        DriverDOB1 = Convert.ToDateTime(_dsApplication.Tables[1].Rows[0]["DOB"].ToString());
                    }
                    if (_dsApplication.Tables[1].Rows.Count > 1 && _dsApplication.Tables[1].Rows[1]["DOB"] != DBNull.Value && _dsApplication.Tables[1].Rows[1]["DOB"].ToString() != string.Empty)
                    {
                        DriverDOB2 = Convert.ToDateTime(_dsApplication.Tables[1].Rows[1]["DOB"].ToString());
                    }
                }
               

                ddlDriver1DOBDay.Text = DriverDOB1.Day.ToString("00");
                ddlDriver1DOBMonth.Text = DriverDOB1.Month.ToString("00");
                ddlDriver1DOBYear.Text = DriverDOB1.Year.ToString("0000");

                ddlDriver2DOBDay.Text = DriverDOB2.Day.ToString("00");
                ddlDriver2DOBMonth.Text = DriverDOB2.Month.ToString("00");
                ddlDriver2DOBYear.Text = DriverDOB2.Year.ToString("0000");

                if (ddlNamedDriver.Text == "0")
                {
                    rfvDriverFirst.Enabled = false;
                    revDriverFirst.Enabled = false;
                    rfvDriver1IDNo.Enabled = false;
                    rfvDriver1LicenseNo.Enabled = false;
                    rfvDriverTwo.Enabled = false;
                    revDriverTwo.Enabled = false;
                    rfvDriver2IDNo.Enabled = false;
                    rfvDriver2LicenseNo.Enabled = false;
                }
                if (ddlNamedDriver.Text == "1")
                {
                    rfvDriverFirst.Enabled = true;
                    revDriverFirst.Enabled = true;
                    rfvDriver1IDNo.Enabled = true;
                    rfvDriver1LicenseNo.Enabled = true;
                    rfvDriverTwo.Enabled = false;
                    revDriverTwo.Enabled = false;
                    rfvDriver2IDNo.Enabled = false;
                    rfvDriver2LicenseNo.Enabled = false;
                }
                if (ddlNamedDriver.Text == "2")
                {
                    rfvDriverFirst.Enabled = true;
                    revDriverFirst.Enabled = true;
                    rfvDriver1IDNo.Enabled = true;
                    rfvDriver1LicenseNo.Enabled = true;
                    rfvDriverTwo.Enabled = true;
                    revDriverTwo.Enabled = true;
                    rfvDriver2IDNo.Enabled = true;
                    rfvDriver2LicenseNo.Enabled = true;
                }
                if (_dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                {
                    if (_dsApplication.Tables[4].Rows[0]["Name"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["Name"].ToString() != string.Empty)
                    {
                        txtCustomerName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                    }
                    if (_dsApplication.Tables[4].Rows[0]["BeneficiaryName"] != DBNull.Value)
                        txtBeneficiary.Text = _dsApplication.Tables[4].Rows[0]["BeneficiaryName"].ToString();
                    if (_dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() != string.Empty
                        && _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() != "true" && _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() != "1")
                    {
                        txtCurrentAddress.Text = _dsApplication.Tables[4].Rows[0]["PresentAddress"].ToString();
                        txtSubDistrict.Text = _dsApplication.Tables[4].Rows[0]["SubDistrict"].ToString();
                        txtStateProvince.Text = _dsApplication.Tables[4].Rows[0]["District"].ToString();
                        txtProvince.Text = _dsApplication.Tables[4].Rows[0]["Province"].ToString();
                        txtPostalCode.Text = _dsApplication.Tables[4].Rows[0]["PostalCode"].ToString();
                    }
                    else
                    {
                        txtCurrentAddress.Text = _dsApplication.Tables[4].Rows[0]["MailingAddress"].ToString();
                        txtSubDistrict.Text = _dsApplication.Tables[4].Rows[0]["MailingSubDistrict"].ToString();
                        txtStateProvince.Text = _dsApplication.Tables[4].Rows[0]["MailingDistrict"].ToString();
                        txtProvince.Text = _dsApplication.Tables[4].Rows[0]["MailingProvince"].ToString();
                        txtPostalCode.Text = _dsApplication.Tables[4].Rows[0]["MailingPostalCode"].ToString();
                    }
                    if (_dsApplication.Tables.Count > 5 && _dsApplication.Tables[5].Rows.Count > 0)
                    {
                        txtPackage.Text = _dsApplication.Tables[5].Rows[0]["CoverTypeDesc"].ToString();
                    }
                    if (_dsApplication.Tables[4].Rows[0]["EngineNumber"] != DBNull.Value)
                        txtEngineNumber.Text = _dsApplication.Tables[4].Rows[0]["EngineNumber"].ToString();
                    if (_dsApplication.Tables[4].Rows[0]["ChassisNumber"] != DBNull.Value)
                        txtChassisNumber.Text = _dsApplication.Tables[4].Rows[0]["ChassisNumber"].ToString();
                   
                    if (_dsApplication.Tables[4].Rows[0]["CarPlateProvince"] != DBNull.Value)
                        txtRegistrationProvince.Text = _dsApplication.Tables[4].Rows[0]["CarPlateProvince"].ToString();

                    DateTime _CreateDate = Convert.ToDateTime(_dsApplication.Tables[4].Rows[0]["CreatedDate"].ToString());
                    ddlApplicationDay.Text = _CreateDate.Day.ToString("00");
                    ddlApplicationMonth.Text = _CreateDate.Month.ToString("00");
                    ddlApplicationYear.Text = _CreateDate.Year.ToString("0000");
                 
                }
                else
                {
                    DateTime _CreateDate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CreatedDate"].ToString());
                   
                    ddlApplicationDay.Text = _CreateDate.Day.ToString("00");
                    ddlApplicationMonth.Text = _CreateDate.Month.ToString("00");
                    ddlApplicationYear.Text = _CreateDate.Year.ToString("0000");
                }
               

                #endregion
            }
            

        }
       

        
    }

    private void LoadNonGGApplicationDetails(DataSet dsApplication)
    {
        ClearFields();
        
        if (dsApplication != null && dsApplication.Tables.Count > 2 && dsApplication.Tables[2].Rows.Count > 0)
        {

            #region Assign Values

           

            if (dsApplication.Tables[2].Rows[0]["Info5"] != DBNull.Value)
            {
                if (!dsApplication.Tables[2].Rows[0]["Info5"].ToString().ToUpper().Contains("OLDQUOTE"))
                {
                    hplUploadDocument.Visible = false;
                    btnSubmit.Enabled = false;
                    lblSummaryMessage.Text = "Found normal application transaction.<br/> This application can NOT be updated.";
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Found normal application transaction.\\nThis application can NOT be updated.');", true);
                }
                else
                {
                    hplUploadDocument.Visible = true;
                    hplUploadDocument.NavigateUrl = "~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQRefNo.Text;
                }
            }
            else
            {
                hplUploadDocument.Visible = false;
                btnSubmit.Enabled = false;
                lblSummaryMessage.Text = "Found normal application transaction.<br/> This application can NOT be updated.";
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Found normal application transaction.\\nThis application can NOT be updated.');", true);
            }

            DateTime policy = dateTimeNow;
            if (dsApplication.Tables[2].Rows[0]["CTPLStart"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["CTPLStart"].ToString() != string.Empty)
            {
                policy = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CTPLStart"].ToString());
            }

          
            ddlPolicyDay.Text = policy.Day.ToString("00");
            ddlPolicyMonth.Text = policy.Month.ToString("00");
            ddlPolicyYear.Text = policy.Year.ToString("0000");

         
            txtEngineNumber.Text = dsApplication.Tables[2].Rows[0]["EngineNumber"].ToString();
            txtChassisNumber.Text = dsApplication.Tables[2].Rows[0]["ChassisNumber"].ToString();
            txtEditLicensePlate.Text = dsApplication.Tables[2].Rows[0]["CarPlate"].ToString();
            txtRegistrationProvince.Text = dsApplication.Tables[2].Rows[0]["CarPlateProvince"].ToString();
            ddlNCB.Text = dsApplication.Tables[2].Rows[0]["NCB"].ToString();

           

            ddlCustomerType.Text = dsApplication.Tables[2].Rows[0]["CustomerType"].ToString();
            txtCustomerName.Text = dsApplication.Tables[2].Rows[0]["CustomerName"].ToString();
            txtPrefix.Text = dsApplication.Tables[2].Rows[0]["Title"].ToString();
            txtBeneficiary.Text = dsApplication.Tables[2].Rows[0]["Beneficiary"].ToString();
            txtInsuredPerson.Text = dsApplication.Tables[2].Rows[0]["Name"].ToString();
            txtContactNumber.Text = dsApplication.Tables[2].Rows[0]["ContactNo"].ToString();
            txtCurrentAddress.Text = dsApplication.Tables[2].Rows[0]["PresentAddress"].ToString();
            txtSubDistrict.Text = dsApplication.Tables[2].Rows[0]["SubDistrict"].ToString();
            txtStateProvince.Text = dsApplication.Tables[2].Rows[0]["District"].ToString();
            txtProvince.Text = dsApplication.Tables[2].Rows[0]["Province"].ToString();
            txtPostalCode.Text = dsApplication.Tables[2].Rows[0]["PostalCode"].ToString();
            txtPackage.Text = dsApplication.Tables[2].Rows[0]["Package"].ToString();

            


            DateTime DriverDOB1 = dateTimeNow.AddYears(-20);
            DateTime DriverDOB2 = dateTimeNow.AddYears(-20);
            
            ddlNamedDriver.Text = dsApplication.Tables[2].Rows[0]["NoOfDriver"].ToString();
            ddlNamedDriver_SelectedIndexChanged(null, null);
            if (ddlNamedDriver.Text == "0")
            {
                txtDriverId1.Text = "0";
                txtDriverId2.Text = "0";
            }
            else if (ddlNamedDriver.Text == "1")
            {
                txtDriverId2.Text = "0";
            }
            if (dsApplication.Tables.Count > 3)
            {
                if (dsApplication.Tables[3].Rows.Count > 0 && dsApplication.Tables[3].Rows[0]["DOB"] != DBNull.Value && dsApplication.Tables[3].Rows[0]["DOB"].ToString() != string.Empty)
                {
                    DriverDOB1 = Convert.ToDateTime(dsApplication.Tables[3].Rows[0]["DOB"].ToString());
                }
                if (dsApplication.Tables[3].Rows.Count > 1 && dsApplication.Tables[3].Rows[1]["DOB"] != DBNull.Value && dsApplication.Tables[3].Rows[1]["DOB"].ToString() != string.Empty)
                {
                    DriverDOB2 = Convert.ToDateTime(dsApplication.Tables[3].Rows[1]["DOB"].ToString());
                }
                if (dsApplication.Tables[3].Rows.Count > 0)
                {
                    txtDriverFirst.Text = dsApplication.Tables[3].Rows[0]["FullName"].ToString();
                    txtDriver1IDNo.Text = dsApplication.Tables[3].Rows[0]["IDNo"].ToString();
                    txtDriver1LicenseNo.Text = dsApplication.Tables[3].Rows[0]["DrivingLicenseNumber"].ToString();
                    txtDriverId1.Text = dsApplication.Tables[3].Rows[0]["CarDriverId"].ToString();
                }
                if (dsApplication.Tables[3].Rows.Count > 1)
                {
                    txtDriverTwo.Text = dsApplication.Tables[3].Rows[1]["FullName"].ToString();
                    txtDriver2IDNo.Text = dsApplication.Tables[3].Rows[1]["IDNo"].ToString();
                    txtDriver2LicenseNo.Text = dsApplication.Tables[3].Rows[1]["DrivingLicenseNumber"].ToString();
                    txtDriverId2.Text = dsApplication.Tables[3].Rows[1]["CarDriverId"].ToString();
                }
            }

            

            ddlDriver1DOBDay.Text = DriverDOB1.Day.ToString("00");
            ddlDriver1DOBMonth.Text = DriverDOB1.Month.ToString("00");
            ddlDriver1DOBYear.Text = DriverDOB1.Year.ToString("0000");

            ddlDriver2DOBDay.Text = DriverDOB2.Day.ToString("00");
            ddlDriver2DOBMonth.Text = DriverDOB2.Month.ToString("00");
            ddlDriver2DOBYear.Text = DriverDOB2.Year.ToString("0000");

           

            DateTime _CreateDate = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CreatedDate"].ToString());
          
            ddlApplicationDay.Text = _CreateDate.Day.ToString("00");
            ddlApplicationMonth.Text = _CreateDate.Month.ToString("00");
            ddlApplicationYear.Text = _CreateDate.Year.ToString("0000");

            if (ddlNamedDriver.Text == "0")
            {
                rfvDriverFirst.Enabled = false;
                revDriverFirst.Enabled = false;
                rfvDriver1IDNo.Enabled = false;
                rfvDriver1LicenseNo.Enabled = false;
                rfvDriverTwo.Enabled = false;
                revDriverTwo.Enabled = false;
                rfvDriver2IDNo.Enabled = false;
                rfvDriver2LicenseNo.Enabled = false;
            }
            if (ddlNamedDriver.Text == "1")
            {
                rfvDriverFirst.Enabled = true;
                revDriverFirst.Enabled = true;
                rfvDriver1IDNo.Enabled = true;
                rfvDriver1LicenseNo.Enabled = true;
                rfvDriverTwo.Enabled = false;
                revDriverTwo.Enabled = false;
                rfvDriver2IDNo.Enabled = false;
                rfvDriver2LicenseNo.Enabled = false;
            }
            if (ddlNamedDriver.Text == "2")
            {
                rfvDriverFirst.Enabled = true;
                revDriverFirst.Enabled = true;
                rfvDriver1IDNo.Enabled = true;
                rfvDriver1LicenseNo.Enabled = true;
                rfvDriverTwo.Enabled = true;
                revDriverTwo.Enabled = true;
                rfvDriver2IDNo.Enabled = true;
                rfvDriver2LicenseNo.Enabled = true;
            }

            
            #endregion

        }
        
      
    }

    public void ClearFields()
    {
       
        lblLoadMessage.Text = string.Empty;
     
        txtChassisNumber.Text = "";
        
        txtRegistrationProvince.Text = "";
        ddlNCB.SelectedIndex = 0;
      
        txtPackage.Text = "";
        txtDriverFirst.Text = "";
        txtDriver1IDNo.Text = "";
        txtDriver1LicenseNo.Text = "";
        txtDriverTwo.Text = "";
        txtDriver2IDNo.Text = "";
        txtDriver2LicenseNo.Text = "";
        txtPrefix.Text = "";
        txtBeneficiary.Text = "";
        txtInsuredPerson.Text = "";
        txtContactNumber.Text = "";
        txtCurrentAddress.Text = "";
        txtSubDistrict.Text = "";
        txtStateProvince.Text = "";
        txtProvince.Text = "";
        txtPostalCode.Text = "";
       
        txtDriverId1.Text = "0";
        txtDriverId2.Text = "0";
    }

    private void LoadPremium()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";

        MyDatabase _db = new MyDatabase();

        DataTable _dtBrokerPremium = new DataTable("tblBrokerPremium");
        _dtBrokerPremium = _db.GetDataTable("Select CXBrokerPremiumID, CXBrokerProviderID from [tblCXBrokerPremium] Where CECarID = " + txtCarId.Text + " And CustomerID = " + txtCustomerId.Text + " And SelectedStatus = 1");

        if (_dtBrokerPremium != null && _dtBrokerPremium.Rows.Count > 0)
        {
            BrokerPremium _brokerPremium = new BrokerPremium();
            BrokerPremiumDB _brokerPremiumdb = new BrokerPremiumDB();

            Int64 _premiumId = Convert.ToInt64(_dtBrokerPremium.Rows[0]["CXBrokerPremiumID"].ToString());
            Int64 _brokerId = Convert.ToInt64(_dtBrokerPremium.Rows[0]["CXBrokerProviderID"].ToString()); ;

            _dtBrokerPremium.Dispose();

            string _ProductType = "CIN";
            Int64 _CECarId = Convert.ToInt64(txtCarId.Text);
            Int64 _CustomerId = Convert.ToInt64(txtCustomerId.Text);

            _brokerPremium = _brokerPremiumdb.GetBrokerPremiumSingleItem(_premiumId, _brokerId, _CECarId, _CustomerId, _ProductType);
            if (_brokerPremium != null)
            {
                txtPremiumId.Text = _brokerPremium.CXBrokerPremiumId.ToString();
                ddlBrokerProvider.Text = _brokerPremium.CXBrokerProviderId.ToString();
                ddlBrokerProvider_SelectedIndexChanged(null, null);
                ddlBrokerCoverType.Text = _brokerPremium.ProviderCoverTypeId.ToString();
                ddlBrokerCoverType_SelectedIndexChanged(null, null);
                txtNetPremium.Text = _brokerPremium.Premium.ToString();

                if (_brokerPremium.DiscountPercentage > 5)
                {
                    ddlDiscountPercentage.Items.Clear();
                    for (int p = _brokerPremium.DiscountPercentage; p >= 0; p--)
                    {
                        ddlDiscountPercentage.Items.Add(new ListItem(p.ToString() + " " + "%", p.ToString()));
                    }
                }

                ddlDiscountPercentage.Text = _brokerPremium.DiscountPercentage.ToString();
                chkSelected.Checked = _brokerPremium.SelectedStatus;
                ddlGarageType.Text = _brokerPremium.WorkShop;
                txtDeductible.Text = _brokerPremium.DEC;
                txtFireTheft.Text = _brokerPremium.FireTheft;
                txtOwnDamage.Text = _brokerPremium.OwnDamage;
                chkCTPL.Checked = _brokerPremium.IsIncludeCMI;
                chkCTPL_CheckedChanged(null, null);
                txtTPPD.Text = _brokerPremium.TPPD;
                txtTPBIA.Text = _brokerPremium.TPBIA;
                txtTPBIP.Text = _brokerPremium.TPBIP;
                txtBailBond.Text = _brokerPremium.BailBound;
                txtNetPremium.Text = _brokerPremium.Premium.ToString();
                txtGrossPremium.Text = _brokerPremium.TotalVMI.ToString();
                if (_brokerPremium.Info3 != string.Empty)
                {
                    ddlVehicleBodyType.Text = _brokerPremium.Info3;
                    ddlVehicleBodyType_SelectedIndexChanged(null, null);
                    txtCTPL.Text = _brokerPremium.TotalCMI.ToString();
                }

                if (_brokerPremium.Info4 == "1")
                {
                    chkCompanyStaff.Checked = true;
                }
                else
                {
                    chkCompanyStaff.Checked = false;
                }

                txtFloodCoverAmount.Text = string.IsNullOrEmpty(_brokerPremium.Info5) ? "0" : _brokerPremium.Info5;

                txtAccModCost.Text = string.IsNullOrEmpty(_brokerPremium.Info7) ? "0" : _brokerPremium.Info7;

                ddlDiscountPercentage.Text = _brokerPremium.DiscountPercentage.ToString();
                ddlDiscountPercentage_SelectedIndexChanged(null, null);
                txtFinalAnnualPremium.Text = _brokerPremium.FinalAnnualPremium.ToString("#0.00");
                txtFinalAnnualPremiumNoDisc.Text = _brokerPremium.FinalAnnualPremiumNoDisc.ToString("#0.00");
                txtPA.Text = _brokerPremium.PADriver.ToString();
                txtMED.Text = _brokerPremium.MedicalExpense.ToString();
                txtEditLicensePlate.Text = _brokerPremium.Info2;
            
                txtPremiumChangeComments.Text = _brokerPremium.Info8;
                txtGrossPremium_TextChanged(null, null);
            }
            else
            {

            }
            _brokerPremium = null;
            _brokerPremiumdb = null;

        }
    }
}
